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.
思路:
使用雙指針,讓前置指針先走n步,然後前後兩個指針一起向前直到前置指針到達鏈表尾部,刪除後指針指向的節點。
同樣使用了附加頭結點來簡化運算。(如刪除的節點是第一個節點的時候)
代碼:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *removeNthFromEnd(ListNode *head, int n) {
if (n == 0 || head == NULL)
return head;
ListNode *pre_head = new ListNode(0);
pre_head->next = head;
// let first point take n steps, and let two points go to the end
ListNode *front(pre_head), *end(pre_head), *pre(pre_head);
for (int i = 0; i < n; ++i) {
front = front->next;
}
while(front != NULL) {
pre = end;
front = front->next;
end = end->next;
}
// delete node
pre->next = end->next;
end->next = NULL;
delete end;
// delete pre-head point
head = pre_head->next;
pre_head->next = NULL;
delete pre_head;
return head;
}
};