Problem:
Given a linked list, remove the nth node from the end of list and return its head.
For 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.
Try to do this in one pass.
Analysis:
The key idea to this problem that the two pointers that we assigned for this linked list should have distance n nodes. Then the back pointer will point to the node we need to remove when the front point point to the last node of this linked list.
Solution:
C++:
ListNode *removeNthFromEnd(ListNode *head, int n) {
if(n == 0)
return head;
ListNode* pBack = head;
ListNode* pFront = head;
for(int i = 0; i < n; ++i) {
pFront = pFront->next;
}
if(pFront == NULL) {
head = pBack->next;
delete pBack;
return head;
}
while(pFront->next != NULL) {
pFront = pFront->next;
pBack = pBack->next;
}
ListNode* pDelete = pBack->next;
pBack->next = pBack->next->next;
delete pDelete;
return head;
}
Java:
Python: