0%

143. Reorder List

O(n) time O(1) space

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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void reorderList(ListNode* head) {
ListNode dummy_head(0);
dummy_head.next = head;
auto slow = &dummy_head, fast = slow; // 如果希望最后slow落在(n - 1) / 2的那个,要从dummy_head开始
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
fast = slow->next;
slow->next = nullptr;
ListNode *prev = nullptr, *curr = fast;
while (curr) {
auto next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
fast = prev;
slow = head;
while (fast) {
auto next = fast->next;
fast->next = slow->next;
slow->next = fast;
slow = fast->next;
fast = next;
}
}
};

O(n) time O(n) space

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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void reorderList(ListNode* head) {
ListNode dummy_head(0);
dummy_head.next = head;
auto slow = &dummy_head, fast = slow;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
fast = slow->next;
slow->next = nullptr;
stack<ListNode *> s;
while (fast) {
s.push(fast);
fast = fast->next;
}
slow = head;
while (!s.empty()) {
auto next = slow->next;
s.top()->next = next;
slow->next = s.top(); s.pop();
slow = next;
}
}
};