-
Notifications
You must be signed in to change notification settings - Fork 7
/
19.cpp
36 lines (36 loc) · 932 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) {
if(n <= 0) return head;
ListNode *prev = head,*behind = head;
n = n + 1;//移动到倒数第n个节点的前一个节点
while(n && prev){
prev = prev->next;
n--;
}
if(n){
if(n > 1) return head; //n太大,直接返回
//删除的是头节点
behind = head;
head = head->next;
delete behind;
return head;
}
while(prev){
prev = prev->next;
behind = behind->next;
}
ListNode *tp = behind->next->next;
delete behind->next ;
behind->next = tp;
return head;
}
};