码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode-Sort List

时间:2014-11-27 01:35:39      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   sp   for   on   div   log   

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

Analsys:

We use Merge Sort.

NOTE: We should practice other sort algorithm, linke Quick Sort and Heap Sort!

Solution:

 1 /**
 2  * Definition for singly-linked list.
 3  * class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) {
 7  *         val = x;
 8  *         next = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     public ListNode sortList(ListNode head) {
14         if (head==null || head.next==null) return head;
15 
16         head = sortListRecur(head);
17         return head;
18     }
19 
20     public ListNode sortListRecur(ListNode head){
21         int len = 1;
22         ListNode curNode = head;
23         while (curNode.next!=null){
24             curNode = curNode.next;
25             len++;
26         }
27 
28         if (len==1) return head;
29         ListNode leftHead = head;
30         ListNode rightHead = null;
31         curNode = head;
32         for (int i=1;i<len/2;i++){
33             curNode = curNode.next;
34         }
35         rightHead = curNode.next;
36         curNode.next = null;
37 
38         leftHead = sortListRecur(leftHead);
39         rightHead = sortListRecur(rightHead);
40 
41         ListNode preHead = new ListNode(0);
42         ListNode end = preHead;
43         while (leftHead!=null || rightHead!=null){
44             if (leftHead==null){
45                 end.next = rightHead;
46                 break;
47             }
48 
49             if (rightHead==null){
50                 end.next = leftHead;
51                 break;
52             }
53 
54             if (leftHead.val<rightHead.val){
55                 end.next = leftHead;
56                 leftHead = leftHead.next;
57                 end = end.next;
58             } else {
59                 end.next = rightHead;
60                 rightHead = rightHead.next;
61                 end = end.next;
62             }
63         }
64 
65         return preHead.next;
66     }
67 
68 }

 

Leetcode-Sort List

标签:style   blog   io   color   sp   for   on   div   log   

原文地址:http://www.cnblogs.com/lishiblog/p/4125465.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!