其他分享
首页 > 其他分享> > 148. 排序链表

148. 排序链表

作者:互联网

归并排序,每次都需根据双指针法将链表分成左右两端

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode sortList(ListNode head) {
        if (head == null || head.next == null)
            return head;
        //每次根据快慢指针法将链表截成两段,左边长度大于等于右边
        ListNode fast = head.next, slow = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        //以slow指针为边界,slow的next是右边的头结点
        ListNode tmp = slow.next;
        slow.next = null;
        ListNode left = sortList(head);
        ListNode right = sortList(tmp);
        ListNode h = new ListNode(0);
        ListNode res = h;
        //将两个子链表归并
        while (left != null && right != null) {
            if (left.val < right.val) {
                h.next = left;
                left = left.next;
            } else {
                h.next = right;
                right = right.next;
            }
            h = h.next;
        }
        //
        h.next = left != null ? left : right;
        return res.next;
    }
}

标签:null,ListNode,val,148,next,链表,right,排序,left
来源: https://blog.csdn.net/qq_43556545/article/details/120784269