-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReorderList.cpp
61 lines (56 loc) · 1.54 KB
/
ReorderList.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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *findMid(ListNode *head){
if(head == NULL) return head;
ListNode *slow = head,*fast = head -> next;
while(fast && fast -> next){
slow = slow -> next;
fast = fast -> next -> next;
}
return slow;
}
ListNode *reverseList(ListNode *head){
ListNode *prev = NULL;
while(head != NULL){
ListNode *tmp = head -> next;
head -> next = prev;
prev = head;
head = tmp;
}
return prev;
}
void mergeList(ListNode *head, ListNode *tail){
ListNode *dummy = new ListNode(-1);
int index = 0;
while(head && tail){
if(index %2 == 0){
dummy -> next = head;
head = head -> next;
}else{
dummy -> next = tail;
tail = tail -> next;
}
dummy = dummy -> next;// don't forget
index ++;
}
if(head != NULL)
dummy -> next = head;
if(tail != NULL)
dummy -> next = tail;
}
void reorderList(ListNode *head) {
if(head == NULL) return;
ListNode *mid = findMid(head);
ListNode *tail = reverseList(mid ->next);
mid-> next = NULL; // break the head and tail
mergeList(head, tail);
}
};