forked from fengvyi/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
143. Reorder List.cpp
41 lines (41 loc) · 1 KB
/
143. Reorder List.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
38
39
40
41
/**
* 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) {
if(!head) return;
ListNode* slow = head, *fast = head;
ListNode* pre = new ListNode(0);
pre->next = slow;
while(fast && fast->next){
pre = pre->next;
slow = slow->next;
fast = fast->next->next;
}
if(fast) slow = slow->next, pre = pre->next;
pre->next = NULL;
ListNode* cur, *next;
pre = NULL, cur = slow;
while(cur){
next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
ListNode* h1 = head, *h2 = pre, *p1, *p2;
while(h1 && h2){
p1 = h1->next;
p2 = h2->next;
h1->next = h2;
h2->next = p1;
h1 = p1;
h2 = p2;
}
}
};