思想:
这题的技巧是删除倒数第n个元素,要求只遍历一遍。
先设两个指针p、q同时指向开头处;
让p先走n步;
然后再让p、q同时走,直到p走到头;
此时,q的下一个就是所要删除的元素。
此题为了方便操作,加入了一个头结点。
/**
* 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 || n == 0)
return head;
ListNode *dummy = new ListNode(-1);
dummy->next = head;
ListNode *p,*q;
p =dummy;
q = dummy;
// let p first go n steps
for(int i=0;i<n;i++) {
if(p->next != NULL) {
p = p->next;
}
else {
return head;
}
}
//then let p & q go to the end together
while(p->next != NULL) {
p = p->next;
q = q->next;
}
ListNode *tmp = q->next;
q->next = q->next->next;
delete tmp;
head = dummy->next;
delete dummy;
return head;
}
};