Node at Given Index in Linked List
Problem​
Given a singly linked list with N nodes and a number X. The task is to find the node at the given index (X)(1 based index) of linked list.
Input:​
First line of input contains number of testcases T. For each testcase, first line of input contains space seperated two integers, length of linked list and X.
Output:​
For each testcase, there will be single line of output containing data at Xth node.
Examples:​
Input:
2
6 5
1 2 3 4 657 76
10 2
8 7 10 8 6 1 20 91 21 2
Output:
657
7
Explanation: Testcase 1: Element at 5th index in the linked list is 657 (1-based indexing).
Your task:​
The task is to complete the function GetNth() which takes head reference and index as arguments and should return the data at Xth position in the linked list.
Constraints:​
Solution​
Python​
def getNth(head, k):
temp = head
for _ in range(0,k-1):
temp = temp.next
return temp.data
Java​
public static int getNth(Node node, int ind) {
Node temp = node;
for(int i=0; i<ind-1; i++)
temp = temp.next;
return temp.data;
}
C++​
int GetNth(struct node* head, int index){
struct node* current = head;
for(int i = 0; i<index-1; i++) {
current = current->next;
}
return current->data;
}
C​
int GetNth(struct node* head, int index) {
struct node* current = head;
for (int i = 0; i < index; i++) {
current = current->next;
}
return current->data;
}