# Middle-题目97：148. Sort List

Sort a linked list in O(n log n) time using constant space complexity.

public class Solution {
public ListNode sortList(ListNode h){
if(h == null || h.next == null)
return h;

/*split into three list*/
ListNode fakesmall = new ListNode(0), small = fakesmall;
ListNode fakelarge = new ListNode(0), large = fakelarge;
ListNode fakeequal = new ListNode(0), equal = fakeequal;

ListNode cur = h; // pivot is h.
while(cur != null){
if(cur.val < h.val){
small.next = cur;
small = small.next;
}
else if(cur.val == h.val){
equal.next = cur;
equal = equal.next;
}
else{
large.next = cur;
large = large.next;
}

cur = cur.next;
}

// put an end.
small.next = equal.next = large.next = null;
// merge them and return . merge reusing below one. merge for quicksort should be simplified.
return merge(merge(sortList(fakesmall.next), sortList(fakelarge.next)),fakeequal.next) ;
}
private ListNode merge(ListNode h, ListNode m){
ListNode fake = new ListNode(0), cur = fake;

while(h != null && m != null){

if(h.val < m.val){
cur.next = h;
h = h.next;
}
else{
cur.next = m;
m = m.next;
}
cur = cur.next;
}

cur.next = (h == null ? m : h);

return fake.next;
}
}

8ms,beats 42.09%,众数8ms,31.36%
cmershen的碎碎念：

#### LeetCode 148 — Sort List（C++ Java Python）

2014-03-02 12:16:54

#### [LeetCode] 148. Sort List java

2017-03-09 16:12:27

#### LeetCode 148:Sort List

2016-01-03 16:13:52

#### LeetCode(148)Sort List

2014-02-04 08:09:01

#### LeetCode 148之Sort List的java题解

2015-05-07 10:00:07

#### 【LEETCODE】148- Sort List [Python]

2016-02-23 17:35:56

#### 148. Sort List (python)

2016-09-19 22:12:26

#### leetcode 148. Sort List 链表 归并排序 和 快排

2017-11-26 18:34:37

#### Leetcode 148 Sort List 单链表排序

2015-08-01 16:52:12

#### 148. Sort List(重要)

2016-08-16 22:09:46