链表归并排序

Posted hglibin

tags:

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

class Solution 
    public ListNode sortList(ListNode head) 
        if (head == null || head.next == null) 
            return head;
        
        ListNode slow = head, fast = head, prev = head;
        while (fast != null && fast.next != null) 
            prev = slow;
            slow = slow.next;
            fast = fast.next.next;
        
        prev.next = null;
        ListNode list1 = sortList(head);
        ListNode list2 = sortList(slow);
        return merge(list1, list2);
    

    public ListNode merge(ListNode list1, ListNode list2) 
        ListNode dummy = new ListNode(-1), curr = dummy;
        while (list1 != null && list2 != null) 
            if (list1.val < list2.val) 
                curr.next = list1;
                list1 = list1.next;
             else 
                curr.next = list2;
                list2 = list2.next;
            
            curr = curr.next;
        
        if (list1 != null) 
            curr.next = list1;
        
        if (list2 != null) 
            curr.next = list2;
        
        return dummy.next;
    

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

链表的快速排序和归并排序

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

链表归并排序插入排序

链表排序之归并排序

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

链表排序-归并排序和快速排序