lintcode-medium-Sort List

本文介绍了一种使用常数空间复杂度实现的链表排序算法,该算法能够在O(n log n)的时间复杂度内完成排序。通过递归地将链表分为两部分,分别排序后再合并的方式实现了高效排序。

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

 

Example

Given 1-3->2->null, sort it to 1->2->3->null.

 

/**
 * Definition for ListNode.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int val) {
 *         this.val = val;
 *         this.next = null;
 *     }
 * }
 */ 
public class Solution {
    /**
     * @param head: The head of linked list.
     * @return: You should return the head of the sorted linked list,
                    using constant space complexity.
     */
    public ListNode sortList(ListNode head) {  
        // write your code here
        
        if(head == null || head.next == null)
            return head;
        
        ListNode slow = head;
        ListNode fast = head;
        
        while(fast != null && fast.next != null && fast.next.next != null){
            slow = slow.next;
            fast = fast.next.next;
        }
        
        ListNode head2 = slow.next;
        slow.next = null;
        
        head = sortList(head);
        head2 = sortList(head2);
        
        head = merge(head, head2);
        
        return head;
    }
    
    public ListNode merge(ListNode head1, ListNode head2){
        
        if(head1 == null)
            return head2;
        if(head2 == null)
            return head1;
        
        ListNode fakehead = new ListNode(0);
        ListNode p = fakehead;
        ListNode p1 = head1;
        ListNode p2 = head2;
        
        while(p1 != null || p2 != null){
            
            int num1 = Integer.MAX_VALUE;
            int num2 = Integer.MAX_VALUE;
            
            if(p1 != null)
                num1 = p1.val;
            if(p2 != null)
                num2 = p2.val;
            
            if(num1 < num2){
                p.next = p1;
                p = p.next;
                p1 = p1.next;
            }
            else{
                p.next = p2;
                p = p.next;
                p2 = p2.next;
            }
            
        }
        
        return fakehead.next;
    }
    
}

 

转载于:https://www.cnblogs.com/goblinengineer/p/5357707.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值