In this tutorial, we have a linked list and we have to find Nth element from the linked list .
Example:
in above example , if we have to find 3nd element from linked list then output is 5
Example – Program to find the Nth element from the linked list
Steps to follow :
- Initialize the count variable to 1 which define the index of node and currentNode variable to Current linked list
- Loop through the linked list
a) if count is equal to the find index then return current
node
b) Increment count
c) change currentNode variable to point to next of the currentNode.
public class KthNodeLinkedList { public static void main(String a[]) { Node firstNode = new Node(10); Node secondNode = new Node(20); Node thirdNode = new Node(30); Node fourthNode = new Node(40); Node fifthNode = new Node(50); Node sixthNode = new Node(60); Node head = firstNode; head.setNext(secondNode); secondNode.setNext(thirdNode); thirdNode.setNext(fourthNode); fourthNode.setNext(fifthNode); fifthNode.setNext(sixthNode); System.out.println("3rd element in linked list : " + getNthNode(head, 3)); System.out.println("4th element in linked list : " + getNthNode(head, 4)); System.out.println("5th element in linked list : " + getNthNode(head, 5)); } public static int getNthNode(Node head, int index) { Node currentNode = head; int count = 1; // index of Node start from while (currentNode != null) { if (count == index) { return currentNode.data; } count = count + 1; currentNode = currentNode.next; } return 0; } } class Node { Node next; int data; public Node(int data) { this.data = data; } public int getData() { return data; } public Node getNextNode() { return next; } public void setNext(Node next) { this.next = next; } @Override public String toString() { return String.format("%d", data); } }
Output
3rd element in linked list : 30
4th element in linked list : 40
5th element in linked list : 50