码迷,mamicode.com
首页 > 编程语言 > 详细

链表排序之归并排序

时间:2019-10-28 21:16:56      阅读:96      评论:0      收藏:0      [点我收藏+]

标签:mergesort   nod   val   code   class   slow   stat   ati   color   

链表排序之归并排序:

public static ListNode mergeSortList(ListNode head){
        if (null == head || null == head.next){
            return head;
        }
        ListNode slow = head;
        ListNode fast = head;
        ListNode pre = head;
        while (null != fast && null != fast.next){
            pre = slow;
            slow = slow.next;
            fast = fast.next.next;
        }
        pre.next = null;
        return mergeTwoSortList(mergeSortList(head), mergeSortList(slow));
    }
    private static ListNode mergeTwoSortList(ListNode head1, ListNode head2){
        if (null == head1){
            return head2;
        }
        if (null == head2){
            return head1;
        }
        ListNode head = new ListNode(-1);
        ListNode cur = head;
        ListNode cur1 = head1;
        ListNode cur2 = head2;
        while (null != cur1 && null != cur2){
            if (cur2.val < cur1.val){
                cur.next = cur2;
                cur2 = cur2.next;
            }else {
                cur.next = cur1;
                cur1 = cur1.next;
            }
            cur = cur.next;
        }
        if (null != cur1){
            cur.next = cur1;
        }
        if (null != cur2){
            cur.next = cur2;
        }
        return head.next;
    }

排序前:6 2 8 4 9 5 1 3 7

排序后:1 2 3 4 5 6 7 8 9

链表排序之归并排序

标签:mergesort   nod   val   code   class   slow   stat   ati   color   

原文地址:https://www.cnblogs.com/earthhouge/p/11754612.html

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