java 单链表的归并排序

Posted

tags:

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

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class MergeList {
    public ListNode sortList(ListNode head) {
        if(head == null || head.next == null) {
            return head;
        }
        
        ListNode slow = head, fast = head;
        while(fast.next!=null && fast.next.next!=null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        ListNode firstHalf = head, secondHalf = slow.next;
        slow.next = null;
        
        ListNode leftList = null, rightList = null;
        if(firstHalf!=secondHalf) {
            leftList = sortList(firstHalf);
            rightList = sortList(secondHalf);
        }
        return mergeTwoLists(leftList, rightList);        
    }
    
    private ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        // 两个有序链表的归并
        ListNode p = l1, q = l2;
        ListNode dummy = new ListNode(-1);
        ListNode r = dummy;
        while(p!=null || q!=null) {
            if(p == null) {
                r.next = q;
                break;
            } else if(q == null) {
                r.next = p;
                break;
            } else if(p.val < q.val) {
                r.next = p;
                p = p.next;
                r = r.next;
            } else {
                r.next = q;
                q = q.next;
                r = r.next;
            }
        }
        return dummy.next;
    }
}

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

精益求精单链表归并排序与快速排序

写给自己看的单链表:归并排序

Java开发前景怎么样?单链表归并排序java

归并排序单链表实现

快速排序,归并排序,堆排序的数组和单链表实现

编程-链表之希尔排序堆排序归并排序快速排序