題目:
Sort a linked list in O(n log n) time using constant space complexity.
題解:
考慮到要求用O(nlogn)的時間複雜度和constant space complexity來sort list,自然而然想到了merge sort方法。同時我們還已經做過了merge k sorted list和merge 2 sorted list。這樣這個問題就比較容易了。
不過這道題要找linkedlist中點,那當然就要用最經典的faster和slower方法,faster速度是slower的兩倍,當faster到鏈尾時,slower就是中點,slower的next是下一半的開始點。
解決了這些問題,題目就很容易解出了。
程式碼如下:
1 public ListNode sortList(ListNode head) {
2 if(head == null|| head.next == null)
3 return head;
4 ListNode slow = head, fast = head, firsthalf = head;
5 while(fast.next!=null&&fast.next.next!=null){
6 slow = slow.next;
7 fast = fast.next.next;
8 }
9 ListNode secondhalf = slow.next;
10 slow.next = null;
11
12 ListNode leftlist = null, rightlist =null;
13 if(firsthalf!=secondhalf){
14 leftlist = sortList(firsthalf);
15 rightlist = sortList(secondhalf);
16 }
17 return mergeTwoLists(leftlist, rightlist);
18 }
19
20 public ListNode mergeTwoLists(ListNode leftlist, ListNode rightlist){
21 if(rightlist == null)
22 return leftlist;
23 if(leftlist == null)
24 return rightlist;
25
26 ListNode fakehead = new ListNode(-1);
27 ListNode ptr = fakehead;
28 while(rightlist!=null&&leftlist!=null){
29 if(rightlist.val<leftlist.val){
30 ptr.next = rightlist;
31 ptr = ptr.next;
32 rightlist = rightlist.next;
33 }else{
34 ptr.next = leftlist;
35 ptr = ptr.next;
36 leftlist = leftlist.next;
37 }
38 }
39
40 if(rightlist!=null)
41 ptr.next = rightlist;
42 if(leftlist!=null)
43 ptr.next = leftlist;
44
45 return fakehead.next;
46 }
2 if(head == null|| head.next == null)
3 return head;
4 ListNode slow = head, fast = head, firsthalf = head;
5 while(fast.next!=null&&fast.next.next!=null){
6 slow = slow.next;
7 fast = fast.next.next;
8 }
9 ListNode secondhalf = slow.next;
10 slow.next = null;
11
12 ListNode leftlist = null, rightlist =null;
13 if(firsthalf!=secondhalf){
14 leftlist = sortList(firsthalf);
15 rightlist = sortList(secondhalf);
16 }
17 return mergeTwoLists(leftlist, rightlist);
18 }
19
20 public ListNode mergeTwoLists(ListNode leftlist, ListNode rightlist){
21 if(rightlist == null)
22 return leftlist;
23 if(leftlist == null)
24 return rightlist;
25
26 ListNode fakehead = new ListNode(-1);
27 ListNode ptr = fakehead;
28 while(rightlist!=null&&leftlist!=null){
29 if(rightlist.val<leftlist.val){
30 ptr.next = rightlist;
31 ptr = ptr.next;
32 rightlist = rightlist.next;
33 }else{
34 ptr.next = leftlist;
35 ptr = ptr.next;
36 leftlist = leftlist.next;
37 }
38 }
39
40 if(rightlist!=null)
41 ptr.next = rightlist;
42 if(leftlist!=null)
43 ptr.next = leftlist;
44
45 return fakehead.next;
46 }