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

[Leetcode] Sort List

时间:2014-06-12 17:59:34      阅读:285      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   java   http   

Question:

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

 

Solution:

Merge sort.

找到链表的中间的那个ListNode.

 

bubuko.com,布布扣
 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)
15             return head;
16         ListNode fast=head;
17         ListNode slow=head;
18         while(fast.next!=null&&fast.next.next!=null){
19             fast=fast.next.next;
20             slow=slow.next;
21         }
22         fast=slow.next;
23         slow.next=null;
24         slow=sortList(head);
25         fast=sortList(fast);
26         return merge(slow,fast);
27     }
28 
29     private ListNode merge(ListNode slow, ListNode fast) {
30         // TODO Auto-generated method stub
31         ListNode head=new ListNode(0);
32         ListNode cur=head;
33         while(slow!=null&&fast!=null){
34             if(slow.val<fast.val){
35                 cur.next=slow;
36                 slow=slow.next;
37             }else{
38                 cur.next=fast;
39                 fast=fast.next;
40             }
41             cur=cur.next;
42         }
43         if(slow!=null){
44             cur.next=slow;
45         }
46         if(fast!=null){
47             cur.next=fast;
48         }
49         return head.next;
50     }
51 }
bubuko.com,布布扣

 

 

 

[Leetcode] Sort List,布布扣,bubuko.com

[Leetcode] Sort List

标签:style   class   blog   code   java   http   

原文地址:http://www.cnblogs.com/wolohaha/p/3781958.html

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