Skip to content

Commit 0b9f979

Browse files
committed
Create Recorder_List.cc
split, reverse and cross-merge
1 parent fb9cee8 commit 0b9f979

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

Recorder_List.cc

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* struct ListNode {
4+
* int val;
5+
* ListNode *next;
6+
* ListNode(int x) : val(x), next(NULL) {}
7+
* };
8+
*/
9+
class Solution {
10+
public:
11+
void reorderList(ListNode *head) {
12+
// IMPORTANT: Please reset any member data you declared, as
13+
// the same Solution instance will be reused for each test case.
14+
head = mergeList(head, reverseList(splitList(head)));
15+
return;
16+
}
17+
private:
18+
ListNode *splitList(ListNode * head) {
19+
if (!head)
20+
return NULL;
21+
ListNode *fast = head, *slow = head;
22+
while (fast && fast->next) {
23+
fast = fast->next->next;
24+
slow = slow->next;
25+
}
26+
fast = slow->next;
27+
slow->next = NULL;
28+
return fast;
29+
}
30+
ListNode *reverseList(ListNode *head) {
31+
ListNode *pre = NULL, *cur = head, *nxt = NULL;
32+
while (cur) {
33+
nxt = cur->next;
34+
cur->next = pre;
35+
pre = cur;
36+
cur = nxt;
37+
}
38+
return pre;
39+
}
40+
ListNode *mergeList(ListNode *ha, ListNode *hb) {
41+
ListNode *ret = NULL;
42+
ListNode **pCur = &ret;
43+
while (ha && hb) {
44+
*pCur = ha;
45+
pCur = &(ha->next);
46+
ha = ha->next;
47+
48+
*pCur = hb;
49+
pCur = &(hb->next);
50+
hb = hb->next;
51+
}
52+
*pCur = ha;
53+
return ret;
54+
}
55+
};

0 commit comments

Comments
 (0)