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

Sort List

时间:2014-12-15 00:06:08      阅读:238      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   sp   for   on   

Sort List 

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

这道题我想过用直接插入,超时了。百度了一下,用的是归并排序,排序以前用的都是数组,这次用链表,不太习惯

参考:http://blog.csdn.net/worldwindjp/article/details/18986737

 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(null == head || null == head.next)
15             return head;                                        //空链表和只有一个节点的链表直接返回head
16         
17         ListNode middle = getMiddle(head);                        //得到中点节点
18         ListNode next = middle.next;
19         middle.next = null;          
20         
21         return merge(sortList(head), sortList(next));
22     }
23     
24     /**
25      * 获取链表的中间位置节点,一个指针走一步,另一个指针走两步
26      * @param head
27      * @return
28      */
29     public ListNode getMiddle(ListNode head){
30         ListNode fast = head;
31         ListNode slow = head;
32         
33         while(null != fast.next && null != fast.next.next){
34             fast = fast.next.next;
35             slow = slow.next;
36         }
37         
38         return slow;
39     }
40     
41     /**
42      * 合并两个有序链表
43      * @param a
44      * @param b
45      */
46     public ListNode merge(ListNode a, ListNode b){
47         ListNode dummyHead = new ListNode(Integer.MIN_VALUE);
48         ListNode cur = dummyHead;
49         while(null != a && null != b){            //开始合并两个链表,放到dummyHead为头结点的链表中
50             if(a.val <= b.val){
51                 cur.next = a;
52                 a = a.next;
53             }
54             else{
55                 cur.next = b;
56                 b = b.next;
57             }
58             cur = cur.next;
59         }//while
60         cur.next = a != null ? a : b;
61         
62         return dummyHead.next;
63     }
64 }

 

Sort List

标签:style   blog   http   io   ar   color   sp   for   on   

原文地址:http://www.cnblogs.com/luckygxf/p/4163875.html

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