# 19. Remove Nth Node From End of List
Given a linked list, remove the n-th node from the end of list and return its head.
Example:
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Follow up:
Could you do this in one pass?
# Solution
Approach 1: Two pass.
Approach 2: One pass.
# Code (Python)
Approach 1:
Approach 2:
# Code (C++)
Approach 1:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
// Two pass.
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode dummyHead(0);
dummyHead.next = head;
ListNode *node = head;
int len = 0;
while (node)
{
len++;
node = node->next;
}
len -= n;
node = &dummyHead;
for (int i = 0; i < len; ++i)
{
node = node->next;
}
node->next = node->next->next;
return dummyHead.next;
}
};
Approach 2:
// One pass.
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode dummyHead(0);
dummyHead.next = head;
ListNode *slow = &dummyHead;
ListNode *fast = &dummyHead;
for (int i = 0; i < n; ++i)
fast = fast->next;
while (fast && fast->next)
{
slow = slow->next;
fast = fast->next;
}
slow->next = slow->next->next;
return dummyHead.next;
}
};