Search Your Topic

config
Friday, 07 July 2017 03:58

Write a function to get Nth node in a Linked List

Written by
Rate this item
(0 votes)

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.

Implementation:

// C program to find n'th node in linked list
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
 
/* Link list node */
struct Node
{
    int data;
    struct Node* next;
};
 
/* Given a reference (pointer to pointer) to the head
    of a list and an int, push a new node on the front
    of the list. */
void push(struct Node** head_ref, int new_data)
{
    /* allocate node */
    struct Node* new_node =
            (struct Node*) malloc(sizeof(struct Node));
 
    /* put in the data  */
    new_node->data  = new_data;
   
    /* link the old list off the new node */
    new_node->next = (*head_ref);
   
    /* move the head to point to the new node */
    (*head_ref)    = new_node;
}
 
/* Takes head pointer of the linked list and index
    as arguments and return data at index*/
int GetNth(struct Node* head, int index)
{
    struct Node* current = head;
    int count = 0; /* the index of the node we're currently
                  looking at */
    while (current != NULL)
    {
       if (count == index)
          return(current->data);
       count++;
       current = current->next;
    }
   
    /* if we get to this line, the caller was asking
       for a non-existent element so we assert fail */
    assert(0);             
}
 
/* Drier program to test above function*/
int main()
{
    /* Start with the empty list */
    struct Node* head = NULL;
   
    /* Use push() to construct below list
     1->12->1->4->1  */
    push(&head, 1);
    push(&head, 4);
    push(&head, 1);
    push(&head, 12);
    push(&head, 1); 
   
    /* Check the count function */
    printf("Element at index 3 is %d", GetNth(head, 3)); 
    getchar();

 

}

Output:
Element at index 3 is 4
Read 76 times
Anish Sir

"I am delighted once again to pen the welcome note to the Tosh!Yas Technologies ."

 Call +91 74 88 34 7779  | Email : anishsingh@live.com

toshiyas.in

Leave a comment

Make sure you enter all the required information, indicated by an asterisk (*). HTML code is not allowed.