Write a GetNth() function that takes a linked list and an integer index and returns the data value stored in the node at that index position.
Example:
Input: 1->10->30->14, index = 2
Output: 30
The node at index 2 is 30
Algorithm:
1. Initialize count = 0
2. Loop through the link list
a. if count is equal to the passed index then return current
node
b. Increment count
c. change current to point to next of the current.
[ad type=”banner”]
Java Programming:
class Node
{
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
class LinkedList
{
Node head;
public int GetNth(int index)
{
Node current = head;
int count = 0;
while (current != null)
{
if (count == index)
return current.data;
count++;
current = current.next;
}
assert(false);
return 0;
}
public void push(int new_data)
{
Node new_Node = new Node(new_data);
new_Node.next = head;
head = new_Node;
}
public static void main(String[] args)
{
LinkedList llist = new LinkedList();
llist.push(1);
llist.push(4);
llist.push(1);
llist.push(12);
llist.push(1);
System.out.println("Element at index 3 is "+llist.GetNth(3));
}
}
Output:
Element at index 3 is 4
Time Complexity: O(n)
[ad type=”banner”]