问题:Remove Nth Node From End of List
难度:medium
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.
解答:
关于倒数的问题,应该引入一个指示标志:用两个指针p, cur,p从头先走n步,然后p、cur一起走,当p走到末尾时,cur也到了目标节点。
凡是涉及到可能删掉链表头节点的处理情况,都应该引入一个虚拟节点来简化处理,即:dummy.next = head;
因为最后要返回的是dummy.next 指针,所以cur从dummy 节点开始, 删除节点时用cur->next = cur->next->next,而不是cur = cur->next。因此在计数的时候,要删除的节点是cur->next
/**
* 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(head == NULL)
return head;
ListNode dummy(head->val + 1); //初始化,只要和head->val不同即可
dummy.next = head;
ListNode* p = &dummy; //计数指示指针
ListNode* cur = &dummy;
for (int i = 0; i < n; i++) {
p = p->next;
}
while (p->next) {
p = p->next;
cur = cur->next;
}
cur->next = cur->next->next;
return dummy.next;
}
};