-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path19.cc
52 lines (51 loc) · 1.2 KB
/
19.cc
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
* 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 *fast = head;
ListNode *slow = head;
for (int i = 0; i < n; ++i) {
if (fast == nullptr) {
return head;
}
fast = fast->next;
}
if (fast == nullptr) {
return head->next;
}
fast = fast->next;
while (fast != nullptr) {
fast = fast->next;
slow = slow->next;
}
slow->next = slow->next->next;
return head;
}
};*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *fast = head;
ListNode *slow = head;
for (int i = 0; i < n; ++i) {
fast = fast->next;
}
if (fast == nullptr) {
return head->next;
}
fast = fast->next;
while (fast != nullptr) {
fast = fast->next;
slow = slow->next;
}
slow->next = slow->next->next;
return head;
}
};