-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathReorder_List.cpp
58 lines (55 loc) · 1.44 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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
ListNode* findMid(ListNode* head) {
ListNode* slow = head;
ListNode* fast = head;
fast = fast->next;
while(fast->next) {
slow = slow->next;
fast = fast->next;
if(fast->next) {
fast = fast->next;
}
}
return slow;
}
ListNode* reverseList(ListNode* head) {
ListNode* iter = head;
ListNode* prev = nullptr;
while(iter) {
ListNode* next = iter->next;
iter->next = prev;
prev = iter;
head = iter;
iter = next;
}
return head;
}
public:
void reorderList(ListNode* head) {
if(!head or !head->next or !head->next->next) {
return;
}
ListNode* mid = findMid(head);
ListNode* head2 = mid->next;
mid->next = nullptr;
head2 = reverseList(head2);
ListNode* backup = head;
while(head2) {
ListNode* next = head->next;
head->next = head2;
ListNode* next2 = head2->next;
head2->next = next;
head = next;
head2 = next2;
}
head = backup;
}
};