lintcode--链表排序

在 O(n log n) 时间复杂度和常数级的空间复杂度下给链表排序。

样例

给出 1->3->2->null,给它排序变成 1->2->3->null.


/**
 * Definition for ListNode.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int val) {
 *         this.val = val;
 *         this.next = null;
 *     }
 * }
思路:
归并排序
 * 根据要求采用先sort再merge的方法,
 * 1.首先找到中点,
 * 2.然后从中点两端分别sort,
 * 3.将两个结果进行merge。
 */


public class Solution {            
    private ListNode findMiddle(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        while (fast.next != null && fast.next.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        //当fast.next.next为空,slow为中点
        return slow;
    }    
    public ListNode merge(ListNode head1, ListNode head2) {
        //Head1的辅助头结点dummy,因为可能在头部插入
        ListNode dummy = new ListNode(0);
        ListNode tail = dummy;
        while (head1 != null && head2 != null) {
            if (head1.val < head2.val) {
                tail.next = head1;
                head1 = head1.next;
            } else {
                tail.next = head2;
                head2 = head2.next;
            }
            
            tail = tail.next;
        }
        //L2或l1可能还有未处理的结点,直接加在尾部即可
        if (head1 != null) {
            tail.next = head1;
        } else {
            tail.next = head2;
        }


        return dummy.next;
    }
        /*
    public ListNode merge(ListNode l1, ListNode l2) {
        // write your code here
        ListNode head;//新链表
        if(l1 == null){return l2;}
        if(l2 == null){return l1;}
        if(l1.val < l2.val){
            head = l1;
            head.next = merge(l1.next,l2);
        }else{
            head = l2;
            head.next = merge(l1,l2.next);
        }
        return head;
    }*/
    public ListNode sortList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode mid = findMiddle(head);
        //需要把左半链表的尾结点的next赋空值
        //(断开),用一个变量来记录右半链表的头
        ListNode nextPart = null;
        if(mid !=null){
        nextPart = mid.next;
        mid.next = null;//断开
        }
        ListNode left = sortList(head);
        ListNode right = sortList(nextPart);
        return merge(left,right);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值