Fork me on GitHub

Reorder List

Description

https://leetcode.com/problems/reorder-list/description/

Solution

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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverse(ListNode* head) {
if (!head || !head->next) return head;
ListNode* ret = reverse(head->next);
head->next->next = head;
head->next = NULL;
return ret;
}

void reorderList(ListNode* head) {
if (!head || !head->next) return;

ListNode* slow = head;
ListNode* quick = head;
while(quick && quick->next && quick->next->next) {
slow = slow->next;
quick = quick->next->next;
}
ListNode* newHead = reverse(slow->next);
slow->next = NULL;

//Merge crossly from head and newHead;
ListNode* cur = head;
ListNode* another = newHead;
while (cur && another) {
ListNode* temp = cur;
cur = cur->next;
temp->next = another;
temp = another;
another = another->next;
temp->next = cur;
}
}
};