Given a linked list. The task is to remove the Nth node from the end of the linked list.
Examples:
Input : LinkedList = 1 ->2 ->3 ->4 ->5 , N = 2 Output : 1 ->2 ->3 ->5 Explanation: Linked list after deleting the 2nd node from last which is 4, is 1 ->2 ->3 ->5
Input : LinkedList = 7 ->8 ->4 ->3 ->2 , N = 1 Output : 7 ->8 ->4 ->3 Explanation: Linked list after deleting the 1st node from last which is 2, is 7 ->8 ->4 ->3
[Expected Approach - 1] Find Equivalent node from Front - O(n) Time and O(1) Space:
To remove the Nth node from the end, first determine the length of the linked list. Then, delete the (length - N + 1)th node from the front.
Follow the steps below to solve the problem:
Traverse the linked list to calculate its length.
Compute the position to delete from the front : nodeToDelete = (length - N + 1).
If nodeToDelete is 1, update the head to the next of head node.
Traverse to the (target - 1)th node and update its next pointer to skip the target node.
Return the modified linked list.
Below is the implementation of the above approach:
C++
// C++ program to delete nth node from last#include<iostream>usingnamespacestd;classNode{public:intdata;Node*next;Node(intnew_data){data=new_data;next=nullptr;}};// Function to remove the Nth node from the endNode*removeNthFromEnd(Node*head,intN){// Calculate the length of the linked listintlength=0;Node*curr=head;while(curr!=nullptr){length++;curr=curr->next;}// Calculate the position to remove from frontinttarget=length-N+1;// If target is 1, remove the head nodeif(target==1){Node*newHead=head->next;// Free memory of the removed nodedeletehead;returnnewHead;}// Traverse to the node just before the targetcurr=head;for(inti=1;i<target-1;i++){curr=curr->next;}// Remove the target nodeNode*nodeToDelete=curr->next;curr->next=curr->next->next;deletenodeToDelete;returnhead;}voidprintList(Node*node){Node*curr=node;while(curr!=nullptr){cout<<" "<<curr->data;curr=curr->next;}}intmain(){// Create a hard-coded linked list: // 1 -> 2 -> 3 -> 4 -> 5Node*head=newNode(1);head->next=newNode(2);head->next->next=newNode(3);head->next->next->next=newNode(4);head->next->next->next->next=newNode(5);intN=2;head=removeNthFromEnd(head,N);printList(head);return0;}
C
// C program to delete nth node from last#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*next;};// Function to remove the Nth node from the endstructNode*removeNthFromEnd(structNode*head,intN){// Calculate the length of the linked listintlength=0;structNode*curr=head;while(curr!=NULL){length++;curr=curr->next;}// Calculate the position to remove from frontinttarget=length-N+1;// If target is 1, remove the head nodeif(target==1){structNode*newHead=head->next;// Free memory of the removed nodefree(head);returnnewHead;}// Traverse to the node just before the targetcurr=head;for(inti=1;i<target-1;i++){curr=curr->next;}// Remove the target nodestructNode*nodeToDelete=curr->next;curr->next=curr->next->next;// Free memory of the removed nodefree(nodeToDelete);returnhead;}voidprintList(structNode*node){structNode*curr=node;while(curr!=NULL){printf(" %d",curr->data);curr=curr->next;}}structNode*createNode(intnew_data){structNode*new_node=(structNode*)malloc(sizeof(structNode));new_node->data=new_data;new_node->next=NULL;returnnew_node;}intmain(){// Create a hard-coded linked list:// 1 -> 2 -> 3 -> 4 -> 5structNode*head=createNode(1);head->next=createNode(2);head->next->next=createNode(3);head->next->next->next=createNode(4);head->next->next->next->next=createNode(5);intN=2;head=removeNthFromEnd(head,N);printList(head);return0;}
Java
// Java program to delete nth node from lastclassNode{intdata;Nodenext;Node(intnew_data){data=new_data;next=null;}}// Class containing the function to remove Nth node from endpublicclassGfG{// Function to remove the Nth node from the endstaticNoderemoveNthFromEnd(Nodehead,intN){// Calculate the length of the linked listintlength=0;Nodecurr=head;while(curr!=null){length++;curr=curr.next;}// Calculate the position to remove from frontinttarget=length-N+1;// If target is 1, remove the head nodeif(target==1){returnhead.next;}// Traverse to the node just before the targetcurr=head;for(inti=1;i<target-1;i++){curr=curr.next;}// Remove the target nodecurr.next=curr.next.next;returnhead;}// This function prints the contents of the linked liststaticvoidprintList(Nodenode){Nodecurr=node;while(curr!=null){System.out.print(" "+curr.data);curr=curr.next;}}publicstaticvoidmain(String[]args){// Create a hard-coded linked list:// 1 -> 2 -> 3 -> 4 -> 5Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);head.next.next.next.next=newNode(5);intN=2;head=removeNthFromEnd(head,N);printList(head);}}
Python
# Python3 program to delete nth node from lastclassNode:def__init__(self,new_data):self.data=new_dataself.next=None# Given the head of a list, remove the Nth node from the enddefremove_nth_from_end(head,N):# Calculate the length of the linked listlength=0curr=headwhilecurrisnotNone:length+=1curr=curr.next# Calculate the position to remove from the fronttarget=length-N+1# If target is 1, remove the head nodeiftarget==1:returnhead.next# Traverse to the node just before the target nodecurr=headfor_inrange(target-2):curr=curr.next# Remove the target nodecurr.next=curr.next.nextreturnheaddefprint_list(node):curr=node;whilecurrisnotNone:print(f" {curr.data}",end="")curr=curr.nextprint()if__name__=="__main__":# Create a hard-coded linked list:# 1 -> 2 -> 3 -> 4 -> 5head=Node(1)head.next=Node(2)head.next.next=Node(3)head.next.next.next=Node(4)head.next.next.next.next=Node(5)N=2head=remove_nth_from_end(head,N)print_list(head)
C#
// C# program to delete nth node from lastusingSystem;classNode{publicintData;publicNodenext;publicNode(intnewData){Data=newData;next=null;}}// Class containing the function to remove the Nth node from// endclassGfG{staticNodeRemoveNthFromEnd(Nodehead,intN){// Calculate the length of the linked listintlength=0;Nodecurr=head;while(curr!=null){length++;curr=curr.next;}// Calculate the position to remove from the frontinttarget=length-N+1;// If target is 1, remove the head nodeif(target==1){returnhead.next;}// Traverse to the node just before the target nodecurr=head;for(inti=1;i<target-1;i++){curr=curr.next;}// Remove the target nodecurr.next=curr.next.next;returnhead;}staticvoidPrintList(Nodenode){Nodecurr=node;while(curr!=null){Console.Write(" "+curr.Data);curr=curr.next;}Console.WriteLine();}staticvoidMain(){// Create a hard-coded linked list:// 1 -> 2 -> 3 -> 4 -> 5Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);head.next.next.next.next=newNode(5);intN=2;head=RemoveNthFromEnd(head,N);PrintList(head);}}
JavaScript
// Javascript program to delete nth node from last classNode{constructor(newData){this.data=newData;this.next=null;}}// Given the head of a list, remove the Nth node from the endfunctionremoveNthFromEnd(head,N){// Calculate the length of the linked listletlength=0;letcurr=head;while(curr!==null){length++;curr=curr.next;}// Calculate the position to remove from the frontlettarget=length-N+1;// If target is 1, remove the head nodeif(target===1){returnhead.next;}// Traverse to the node just before the target nodecurr=head;for(leti=1;i<target-1;i++){curr=curr.next;}// Remove the target nodecurr.next=curr.next.next;returnhead;}functionprintList(node){letcurr=node;while(curr!==null){process.stdout.write(" "+curr.data);curr=curr.next;}console.log();}// Create a hard-coded linked list:// 1 -> 2 -> 3 -> 4 -> 5lethead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);head.next.next.next.next=newNode(5);letN=2;head=removeNthFromEnd(head,N);printList(head);
Output
1 2 3 5
Time Complexity: O(2n), due to traversing the list twice (once for length calculation and once for node removal). Auxiliary Space: O(1).
[Expected Approach - 2] Using Fast and Slow Pointer - O(n) Time and O(1) Space:
The idea is to first move the fast pointer N steps ahead, then move both fast and slow pointers together until fast reaches the end. The slow pointer will then be just before the node to be removed, allowing to update the next pointer to skip the target node.
Below is the implementation of the above approach:
C++
// C++ program to delete nth node from last#include<iostream>usingnamespacestd;classNode{public:intdata;Node*next;Node(intnew_data){data=new_data;next=nullptr;}};// Function to remove the Nth node from the endNode*removeNthFromEnd(Node*head,intN){// Initialize two pointers, fast and slowNode*fast=head;Node*slow=head;// Move fast pointer N steps aheadfor(inti=0;i<N;i++){if(fast==nullptr)returnhead;fast=fast->next;}// If fast is null, remove the head nodeif(fast==nullptr){Node*newHead=head->next;deletehead;returnnewHead;}// Move both pointers until fast reaches the endwhile(fast->next!=nullptr){fast=fast->next;slow=slow->next;}// Remove the Nth node from the endNode*nodeToDelete=slow->next;slow->next=slow->next->next;deletenodeToDelete;returnhead;}voidprintList(Node*node){Node*curr=node;while(curr!=nullptr){cout<<" "<<curr->data;curr=curr->next;}}intmain(){// Create a hard-coded linked list: // 1 -> 2 -> 3 -> 4 -> 5Node*head=newNode(1);head->next=newNode(2);head->next->next=newNode(3);head->next->next->next=newNode(4);head->next->next->next->next=newNode(5);intN=2;head=removeNthFromEnd(head,N);printList(head);return0;}
C
// C program to delete nth node from last#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*next;};// Function to remove the Nth node from the endstructNode*removeNthFromEnd(structNode*head,intN){// Initialize two pointers, fast and slowstructNode*fast=head;structNode*slow=head;// Move fast pointer N steps aheadfor(inti=0;i<N;i++){if(fast==NULL)returnhead;fast=fast->next;}// If fast is NULL, remove the head nodeif(fast==NULL){structNode*newHead=head->next;free(head);returnnewHead;}// Move both pointers until fast reaches the endwhile(fast->next!=NULL){fast=fast->next;slow=slow->next;}// Remove the Nth node from the endstructNode*nodeToDelete=slow->next;slow->next=slow->next->next;free(nodeToDelete);returnhead;}voidprintList(structNode*node){structNode*curr=node;while(curr!=NULL){printf(" %d",curr->data);curr=curr->next;}}structNode*createNode(intnew_data){structNode*new_node=(structNode*)malloc(sizeof(structNode));new_node->data=new_data;new_node->next=NULL;returnnew_node;}intmain(){// Create a hard-coded linked list:// 1 -> 2 -> 3 -> 4 -> 5structNode*head=createNode(1);head->next=createNode(2);head->next->next=createNode(3);head->next->next->next=createNode(4);head->next->next->next->next=createNode(5);intN=2;head=removeNthFromEnd(head,N);printList(head);return0;}
Java
// Java program to delete nth node from lastclassNode{intdata;Nodenext;Node(intnew_data){data=new_data;next=null;}}// Class containing the function to remove Nth node from endpublicclassGfG{// remove the Nth node from laststaticNoderemoveNthFromEnd(Nodehead,intN){// Initialize two pointers, fast and slowNodefast=head;Nodeslow=head;// Move fast pointer N steps aheadfor(inti=0;i<N;i++){if(fast==null)returnhead;fast=fast.next;}// If fast is null, remove the head nodeif(fast==null){returnhead.next;}// Move both pointers until fast reaches the endwhile(fast.next!=null){fast=fast.next;slow=slow.next;}// Remove the Nth node from the endslow.next=slow.next.next;returnhead;}// This function prints the contents of the linked liststaticvoidprintList(Nodenode){Nodecurr=node;while(curr!=null){System.out.print(" "+curr.data);curr=curr.next;}}publicstaticvoidmain(String[]args){// Create a hard-coded linked list:// 1 -> 2 -> 3 -> 4 -> 5Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);head.next.next.next.next=newNode(5);intN=2;head=removeNthFromEnd(head,N);printList(head);}}
Python
# Python3 program to delete nth node from lastclassNode:def__init__(self,new_data):self.data=new_dataself.next=None# Given the head of a list, remove the Nth node from the enddefremove_nth_from_end(head,N):# Initialize two pointers, fast and slowfast=headslow=head# Move fast pointer N steps aheadfor_inrange(N):iffastisNone:returnheadfast=fast.next# If fast is None, remove the head nodeiffastisNone:returnhead.next# Move both pointers until fast reaches the endwhilefast.nextisnotNone:fast=fast.nextslow=slow.next# Remove the Nth node from the endslow.next=slow.next.nextreturnheaddefprint_list(node):curr=node;whilecurrisnotNone:print(f" {curr.data}",end="")curr=curr.nextprint()if__name__=="__main__":# Create a hard-coded linked list:# 1 -> 2 -> 3 -> 4 -> 5head=Node(1)head.next=Node(2)head.next.next=Node(3)head.next.next.next=Node(4)head.next.next.next.next=Node(5)N=2head=remove_nth_from_end(head,N)print_list(head)
C#
// C# program to delete nth node from lastusingSystem;classNode{publicintData;publicNodenext;publicNode(intnewData){Data=newData;next=null;}}// Class containing the function to // remove the Nth node from endclassGfG{staticNodeRemoveNthFromEnd(Nodehead,intN){// Initialize two pointers, fast and slowNodefast=head;Nodeslow=head;// Move fast pointer N steps aheadfor(inti=0;i<N;i++){if(fast==null)returnhead;fast=fast.next;}// If fast is null, remove the head nodeif(fast==null){returnhead.next;}// Move both pointers until fast reaches the endwhile(fast.next!=null){fast=fast.next;slow=slow.next;}// Remove the Nth node from the endslow.next=slow.next.next;returnhead;}staticvoidPrintList(Nodenode){Nodecurr=node;while(curr!=null){Console.Write(" "+curr.Data);curr=curr.next;}Console.WriteLine();}staticvoidMain(){// Create a hard-coded linked list:// 1 -> 2 -> 3 -> 4 -> 5Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);head.next.next.next.next=newNode(5);intN=2;head=RemoveNthFromEnd(head,N);PrintList(head);}}
JavaScript
// JavaScript program to delete nth node from last classNode{constructor(newData){this.data=newData;this.next=null;}}// Given the head of a list, remove the // Nth node from the endfunctionremoveNthFromEnd(head,N){// Initialize two pointers, fast and slowletfast=head;letslow=head;// Move fast pointer N steps aheadfor(leti=0;i<N;i++){if(fast===null)returnhead;fast=fast.next;}// If fast is null, remove the head nodeif(fast===null){returnhead.next;}// Move both pointers until fast reaches the endwhile(fast.next!==null){fast=fast.next;slow=slow.next;}// Remove the Nth node from the endslow.next=slow.next.next;returnhead;}functionprintList(node){letcurr=node;while(curr!==null){process.stdout.write(" "+curr.data);curr=curr.next;}console.log();}// Create a hard-coded linked list:// 1 -> 2 -> 3 -> 4 -> 5lethead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);head.next.next.next.next=newNode(5);letN=2;head=removeNthFromEnd(head,N);printList(head);
Output
1 2 3 5
Time complexity: O(n), due to a single pass through the list with the two pointers. Space complexity: O(1).
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.