问题
https://leetcode.com/problems/remove-nth-node-from-end-of-list/
解法
设置两个指针,第一个指向第一个,第二个指向第n+1个,这样同时向后移动两个指针,当第二个到尾部时,第一个正好在要删除的位置的前一个。
小tips:在链表头上加一个头结点, 就不用考虑删除链表头的问题了。
/**
* 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) {
ListNode Head = ListNode(0);
Head.next = head;
ListNode* first = &Head;
ListNode* sec = &Head;
for (int i=0; i<n+1; i++)
sec = sec->next;
while(sec) sec= sec->next, first= first->next;
ListNode* del = first->next;
first->next = first->next->next;
delete del;
return Head.next;
}
};