链表排序之归并排序

Posted earthhouge

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了链表排序之归并排序相关的知识,希望对你有一定的参考价值。

链表排序之归并排序:

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

以上是关于链表排序之归并排序的主要内容,如果未能解决你的问题,请参考以下文章

链表归并排序

链表归并排序

排序算法之归并排序

链表的排序(归并排序+快慢指针)

自然归并排序一个链表

c++链表归并排序的迭代版本