-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReorder List.cpp
93 lines (85 loc) · 1.79 KB
/
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include <iostream>
using namespace std;
/**
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You must do this in-place without altering the nodes' values.
Example
For example,
Given 1->2->3->4->null, reorder it to 1->4->2->3->null.
*/
//* Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *reverse(ListNode *list) {
ListNode *pre = NULL;
while(list) {
ListNode *tmp = list->next;
list->next = pre;
pre = list;
list = tmp;
}
return pre;
}
ListNode *merge(ListNode *l1, ListNode *l2) {
ListNode *dummy = new ListNode(-1);
ListNode *last = dummy;
bool flag = true;
while(l1 && l2) {
if(flag) {
last->next = l1;
l1 = l1->next;
flag = !flag;
}
else {
last->next = l2;
l2 = l2->next;
flag = !flag;
}
last = last->next;
}
if(l2) {
last->next = l2;
}
return dummy->next;
}
void reorderList(ListNode* head) {
if(!head || !head->next) return;
ListNode *slow = head;
ListNode *fast = head->next;
while(fast->next && fast->next->next) {
slow = slow->next;
fast = fast->next->next;
}
ListNode *l1 = head;
ListNode *l2 = slow->next;
slow->next = NULL;
l2 = reverse(l2);
head = merge(l1, l2);
return;
}
};
ListNode *createList(int len) {
ListNode *dummy = new ListNode(-1);
ListNode *last = dummy;
for(int i = 1; i <= len; i++) {
last->next = new ListNode(i);
last = last->next;
}
return dummy->next;
}
int main() {
ListNode *l = createList(4);
Solution s;
s.reorderList(l);
while(l) {
cout << l->val << endl;
l = l->next;
}
return 0;
}