VOOZH about

URL: https://www.geeksforgeeks.org/dsa/delete-nth-node-from-the-end-of-the-given-linked-list/

⇱ Delete Nth node from the end of the given linked list - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Delete Nth node from the end of the given linked list

Last Updated : 14 Jun, 2026

Given a linked list and an integer n, delete the nth node from the end of the given 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

👁 frame_2

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  

👁 frame_1

[Naive Approach] Using Deletion from Front Approach - O(n) Time and O(1) Space

To remove the nth node from the end, first calculate the length of the linked list. Then, convert the problem into deleting the (length - n + 1)th node from the beginning of the list.

  • Traverse the linked list to calculate its length.
  • Compute the position of the node to delete from the front: nodeToDelete = (length - n + 1)
  • If nodeToDelete is 1, move the head to the next node.
  • Traverse the list till the (nodeToDelete - 1)th node.
  • Update its next pointer to skip the target node.
  • Return the modified linked list.

Output
1 2 3 5 

[Expected Approach] Using Fast and Slow Pointers - 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.

  • Create a dummy node and connect it before the head node to handle edge cases easily.
  • Initialize two pointers, fast and slow, at the dummy node.
  • Move the fast pointer n + 1 steps ahead to maintain a gap of n nodes.
  • Move both fast and slow pointers together until fast reaches nullptr.
  • The slow pointer now points to the node just before the target node, so update its next pointer to skip the target node.
  • Delete the target node and return the updated linked list starting from dummy->next.

Output
1 2 3 5 
Comment