Program for n’th node from the end of a Linked List

Given a Linked List and a number n, write a function that returns the value at the n’th node from end of the Linked List.

For example, if input is below list and 3 = 2, then output is “B”

Method 1 (Use length of linked list)1) Calculate the length of Linked List. Let the length be len.2) Print the (len – n + 1)th node from the begining of the Linked List.

// Simple C program to find n'th node from end

#include<stdio.h>

#include<stdlib.h>

/* Link list node */

structNode

{

intdata;

structNode* next;

};

/* Function to get the nth node from the last of a linked list*/

voidprintNthFromLast(structNode* head, intn)

{

intlen = 0, i;

structNode *temp = head;

// 1) count the number of nodes in Linked List

while(temp != NULL)

{

temp = temp->next;

len++;

}

// check if value of n is not more than length of the linked list

if(len < n)

return;

temp = head;

// 2) get the (n-len+1)th node from the begining

for(i = 1; i < len-n+1; i++)

temp = temp->next;

printf("%d", temp->data);

return;

}

voidpush(structNode** head_ref, intnew_data)

{

/* allocate node */

structNode* new_node =

(structNode*) malloc(sizeof(structNode));

/* 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;

}

/* Drier program to test above function*/

intmain()

{

/* Start with the empty list */

structNode* head = NULL;

// create linked 35->15->4->20

push(&head, 20);

push(&head, 4);

push(&head, 15);

push(&head, 35);

printNthFromLast(head, 5);

return0;

}

Output:

35

Following is a recursive C code for the same method. Thanks to Anuj Bansal for providing following code.

voidprintNthFromLast(structNode* head, intn)

{

staticinti = 0;

if(head == NULL)

return;

printNthFromLast(head->next, n);

if(++i == n)

printf("%d", head->data);

}

ime Complexity: O(n) where n is the length of linked list.

Method 2 (Use two pointers) Maintain two pointers – reference pointer and main pointer. Initialize both reference and main pointers to head. First move reference pointer to n nodes from head. Now move both pointers one by one until reference pointer reaches end. Now main pointer will point to nth node from the end. Return main pointer.