-
Notifications
You must be signed in to change notification settings - Fork 262
Expand file tree
/
Copy pathremove-nth-node-from-end-of-list.cpp
More file actions
47 lines (42 loc) · 1010 Bytes
/
Copy pathremove-nth-node-from-end-of-list.cpp
File metadata and controls
47 lines (42 loc) · 1010 Bytes
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
// Time: O(n)
// Space: O(1)
/**
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: The first node of linked list.
* @param n: An integer.
* @return: The head of linked list.
*/
ListNode *removeNthFromEnd(ListNode *head, int n) {
ListNode dummy{0};
dummy.next = head;
auto slow = &dummy;
auto fast = &dummy;
// fast is n-step ahead.
while (n > 0) {
fast = fast->next;
--n;
}
// When fast reaches the end, slow must be nth to last node.
while (fast->next != nullptr) {
slow = slow->next;
fast = fast->next;
}
auto node_to_delete = slow->next;
slow->next = slow->next->next;
delete node_to_delete;
return dummy.next;
}
};