Description: You are given pointer to head node of a linked list. Your task is to get the data in the nth node of this given linked list.

 

If video does not load, Click here

Algorithm:

•       Initialize a current pointer to point to head of linked list

•       2. Initialize a count variable = 0

•       3. Loop through the linked list

o    a. if the count is equal to the passed value of N  then return current node

o    b. Increment count

o    c. change current  pointer to point to next node.

Implementation using C:

 
/* Linked List Node structure */
struct node
{
    int data;
    struct node* next;
}
/* Function to find the data in Nth Node */
int FindNode( struct node* head, int N)
{
//Initialize a current pointer to point to head of linked list
    struct node* current = head;
// Initialize a count variable = 0
 int count = 0;    
//Loop through the linked list
 while (current != NULL)
 {//if the count is equal to the passed value of N  then return current node
       if (count == N)
       return(current->data);
//Increment count
       count++;
//change current  pointer to point to next node
       current = current->next;
    }}
 
Time Complexity:

O(n)

Go to top