-
Notifications
You must be signed in to change notification settings - Fork 0
/
19.cpp
36 lines (33 loc) · 881 Bytes
/
19.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
* 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) {
list<ListNode*> buffer;
ListNode* curr = head;
while(curr != NULL) {
if (buffer.size() < n + 1) {
buffer.push_back(curr);
}
else {
buffer.pop_front();
buffer.push_back(curr);
}
curr = curr -> next;
}
// 如果buffer长度为n而非n+1,即被移除的结点是head
if (buffer.size() == n) {
head = head -> next;
}
else {
buffer.front() -> next = buffer.front() -> next -> next;
}
return head;
}
};