forked from iphkwan/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathRecorder_List.cc
55 lines (54 loc) · 1.39 KB
/
Recorder_List.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
53
54
55
/**
* 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) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
head = mergeList(head, reverseList(splitList(head)));
return;
}
private:
ListNode *splitList(ListNode * head) {
if (!head)
return NULL;
ListNode *fast = head, *slow = head;
while (fast && fast->next) {
fast = fast->next->next;
slow = slow->next;
}
fast = slow->next;
slow->next = NULL;
return fast;
}
ListNode *reverseList(ListNode *head) {
ListNode *pre = NULL, *cur = head, *nxt = NULL;
while (cur) {
nxt = cur->next;
cur->next = pre;
pre = cur;
cur = nxt;
}
return pre;
}
ListNode *mergeList(ListNode *ha, ListNode *hb) {
ListNode *ret = NULL;
ListNode **pCur = &ret;
while (ha && hb) {
*pCur = ha;
pCur = &(ha->next);
ha = ha->next;
*pCur = hb;
pCur = &(hb->next);
hb = hb->next;
}
*pCur = ha;
return ret;
}
};