-
Notifications
You must be signed in to change notification settings - Fork 619
Description
The issue contains a LeetCode Question to Remove Nth Node from Linked List.
Algorithm: Remove the Nth Node from the End of a Linked List
Input: Head pointer of a linked list and integer n (the position from the end to remove).
Output: Head pointer of the modified linked list after deletion.
Steps:
Create a dummy node that points to the head of the linked list.
This helps handle cases where the node to be deleted is the first node.
Initialize two pointers:
head → points to the actual head of the list.
dummy → points to the dummy node (used for traversal).
Move head forward by n steps.
This ensures there is a gap of n nodes between head and dummy.
Move both head and dummy together one step at a time until head reaches the end (nullptr).
At this point, dummy will be pointing to the node just before the node that must be deleted.
Remove the target node by skipping it:
dummy->next = dummy->next->next.
Return the modified list starting from res->next (since res was the dummy node).
Time Complexity: O(L), where L = number of nodes in the list
Space Complexity: O(1) — only uses pointers, no extra memory