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.
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.
C Programming:
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node* next;
};
void printNthFromLast(struct node* head, int n)
{
int len = 0, i;
struct node *temp = head;
while (temp != NULL)
{
temp = temp->next;
len++;
}
if (len < n)
return;
temp = head;
for (i = 1; i < len-n+1; i++)
temp = temp->next;
printf ("%d", temp->data);
return;
}
void push(struct node** head_ref, int new_data)
{
struct node* new_node =
(struct node*) malloc(sizeof(struct node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
int main()
{
struct node* head = NULL;
push(&head, 20);
push(&head, 4);
push(&head, 15);
push(&head, 35);
printNthFromLast(head, 5);
return 0;
}
Output:
35
[ad type=”banner”]
Following is a recursive C code for the same method. Thanks to Anuj Bansal for providing following code.
C Programming:
void printNthFromLast(struct node* head, int n)
{
static int i = 0;
if (head == NULL)
return;
printNthFromLast(head->next, n);
if (++i == n)
printf("%d", head->data);
}
Time 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.
Python Programming:
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
def printNthFromLast(self, n):
main_ptr = self.head
ref_ptr = self.head
count = 0
if(self.head is not None):
while(count < n ):
if(ref_ptr is None):
print "%d is greater than the no. pf \
nodes in list" %(n)
return
ref_ptr = ref_ptr.next
count += 1
while(ref_ptr is not None):
main_ptr = main_ptr.next
ref_ptr = ref_ptr.next
print "Node no. %d from last is %d " %(n, main_ptr.data)
llist = LinkedList()
llist.push(20)
llist.push(4)
llist.push(15)
llist.push(35)
llist.printNthFromLast(4)
Output:
Node no. 4 from last is 35
Time Complexity: O(n) where n is the length of linked list
[ad type=”banner”]