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

LeetCode Sort List

时间:2014-09-13 13:15:45      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   ar   for   art   div   sp   

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

归并排序的基本思想是:找到链表的middle节点,然后递归对前半部分和后半部分分别进行归并排序,最后对两个以排好序的链表进行Merge。

 

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    
        private ListNode getMiddle(ListNode head) {
        ListNode slow = head,fast=head;
        
        while (fast.next!=null&&fast.next.next!=null) {
            slow=slow.next;
            fast=fast.next.next;
            
        }
        return slow;
    }
    private ListNode     merge(ListNode a, ListNode b) {
        ListNode first=new ListNode(-1);
        ListNode curr = first;
        while (a!=null&&b!=null) {
            if (a.val<=b.val) {
                curr.next=a;
                a=a.next;
            }else {
                curr.next=b;
                b=b.next;
            }
            curr=curr.next;
        }
        
        if (a!=null) {
            curr.next=a;
        }else {
            curr.next=b;
        }
        return first.next;
        
    }

    public ListNode sortList(ListNode head) {
            if (head==null||head.next==null) {
                return head;
            }
            ListNode middleNode = getMiddle(head);
            ListNode nextPart = middleNode.next;
            middleNode.next=null;
            return merge(sortList(head),sortList(nextPart));

    }
}

 

LeetCode Sort List

标签:style   blog   color   io   ar   for   art   div   sp   

原文地址:http://www.cnblogs.com/birdhack/p/3969664.html

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