单链表排序

https://leetcode.com/problems/sort-list/
http://www.acmerblog.com/leetcode-sort-list-5982.html

归并排序

package bigo;

class ListNode{
    int val;
    ListNode next;

    ListNode(int x) { val = x; }
}


public class link_sort {

    private static ListNode merge(ListNode list1, ListNode list2){
        if(list1 == null) return list2;
        if(list2 == null) return list1;

        ListNode newHead = new ListNode(0);

        ListNode last = newHead;
        while(list1 != null && list2 != null){
            if(list1.val < list2.val){
                last.next = list1;
                list1 = list1.next;
            }else{
                last.next = list2;
                list2 = list2.next;
            }

            last = last.next;
        }
        if(list1 != null)
            last.next = list1;
        else if(list2 != null)
            last.next = list2;

        return newHead.next;

    }

    private static ListNode sortList(ListNode head){
        if(head == null || head.next == null)  return head;

        ListNode slow = head;
        ListNode fast = head;

        while(fast.next != null && fast.next.next != null){
            slow = slow.next;
            fast = fast.next.next;
        }
        //经过上面的移动后, slow 就到了中间了 。 因为fast每次移动两步,slow每次移动一步。

        ListNode list2 = slow.next;
        slow.next = null;
        //将链表分成两条。 head  和   list2

        head = sortList(head);
        list2 = sortList(list2);

        return merge(head, list2);


    }

    public static void  main(String [] arg){
        ListNode l1 = new ListNode(8);
        ListNode l2 = new ListNode(7);
        ListNode l3 = new ListNode(5);
        ListNode l4 = new ListNode(4);
        ListNode l5 = new ListNode(1);

        l1.next = l2;
        l2.next = l3;
        l3.next = l4;
        l4.next = l5;

        l1 = sortList(l1);

        while(l1 != null){
            System.out.println(l1.val + " ");
            l1 = l1.next;
        }

    }


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值