forked from Ext4FAT/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortList.cpp
More file actions
32 lines (30 loc) · 764 Bytes
/
SortList.cpp
File metadata and controls
32 lines (30 loc) · 764 Bytes
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
#define MYNEXT(_TMP,_HEAD) \
_TMP->next=_HEAD; \
_TMP=_HEAD; \
_HEAD=_HEAD->next;
ListNode* mergeList(ListNode* h1, ListNode* h2){
ListNode *head, *tmp;
for(tmp = head = new ListNode(0);h1 && h2;)
if(h1->val < h2->val){
MYNEXT(tmp,h1)
}
else{
MYNEXT(tmp,h2)
}
if(h1) tmp->next = h1;
else tmp->next = h2;
return head->next;
}
ListNode* sortList(ListNode* head) {
if(!head||!head->next) return head;
//find the middle;
ListNode *slow, *fast;
for(slow = fast = head; fast->next && fast->next->next; slow = slow->next, fast = fast->next->next) ;
fast = slow->next;
slow->next = NULL;
//recur sort the list
slow = sortList(head);
fast = sortList(fast);
//merge two sorted list
return mergeList(slow,fast);
}