forked from pezy/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
solution.h
55 lines (50 loc) · 1.36 KB
/
solution.h
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
#include <cstddef>
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
ListNode* reverseList(ListNode *head) {
ListNode *newHead = NULL;
while (head) {
ListNode *next = head->next;
head->next = newHead;
newHead = head;
head = next;
}
return newHead;
}
ListNode *shuffleMerge(ListNode *a, ListNode *b) {
ListNode *ret = NULL, **lastRef = &ret;
while (a && b) {
moveNode(lastRef, &a);
lastRef = &((*lastRef)->next);
moveNode(lastRef, &b);
lastRef = &((*lastRef)->next);
}
*lastRef = a ? a : b;
return ret;
}
void moveNode(ListNode **destRef, ListNode **sourceRef) {
ListNode *newNode = *sourceRef;
*sourceRef = newNode->next;
newNode->next = *destRef;
*destRef = newNode;
}
public:
void reorderList(ListNode *head) {
if (head == NULL) return;
ListNode *slow = head, *fast = head->next;
while (fast) {
fast = fast->next;
if (fast) {
slow = slow->next;
fast = fast->next;
}
}
ListNode *back = reverseList(slow->next);
slow->next = NULL;
head = shuffleMerge(head, back);
}
};