-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path19_2.cpp
37 lines (32 loc) · 821 Bytes
/
19_2.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
37
// Author: Tong Xu
// Date: 1/3/2020
// 1 pass solution + fast/slow pointer
/**
* 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 *dummy = new ListNode(-1);
dummy->next = head;
ListNode *slow = dummy, *fast = dummy;
int i = 0;
while(i < n) {
fast = fast->next;
i++;
}
while(fast->next != NULL) { // this line of code is a little tricky
slow = slow->next;
fast = fast->next;
}
slow->next = slow->next->next;
ListNode* result = dummy->next;
delete dummy;
return result;
}
};