题目来源

148. 排序链表 - 力扣(LeetCode)

代码

/**
 * 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 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 l1 = sortList(head);
        ListNode l2 = sortList(slow);

        //合并
        return merge(l1,l2);
    }

    private ListNode merge(ListNode l1, ListNode l2) {
        //合并后返回的链表(有额外头结点)
        ListNode dummy = new ListNode(0);
        ListNode curr = dummy;

        //比大小合并
        while(l1!=null && l2!=null) {
            if(l1.val <= l2.val) {
                curr.next = l1;
                l1 = l1.next;
            } else {
                curr.next = l2;
                l2 = l2.next;
            }
            curr = curr.next;
        }

        //剩余链表的接上
        curr.next = l1==null?l2:l1;

        return dummy.next;
    }

}

代码分析

1.通过快慢指针 找中点

用于分割链表

2.分割链表

通过让左边链表链表尾 prev.next = null;

3.左右子链表递归排序

不断缩小规模,缩到只有一个结点,然后不断回调

4.合并

通过比大小,排序,来合并左右子链表。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐