给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。

示例 1:
image

输入:head = [4,2,1,3]
输出:[1,2,3,4]
示例 2:
image

输入:head = [-1,5,3,4,0]
输出:[-1,0,3,4,5]
示例 3:

输入:head = []
输出:[]



方法一:使用每个节点的值进行排序,再根据 val 创建节点,返回新列表
执行 12 ms

List<Integer> valueList = new ArrayList<Integer>();
        ListNode cur = head;
        while (cur != null) {
            valueList.add(cur.val);
            cur = cur.next;
        }
        Collections.sort(valueList);

        ListNode dummy = new ListNode();
        ListNode tail = dummy;
        for (int val : valueList) {
            tail.next = new ListNode(val);
            tail = tail.next;
        }
        return dummy.next;
}

方法二:list 加入 node,写比较器
执行 291 ms

List<ListNode> nodeList = new ArrayList<ListNode>();
        ListNode cur = head;
        while (cur != null) {
            nodeList.add(cur);
            cur = cur.next;
        }

        Collections.sort(nodeList, new Comparator<ListNode>() {
            public int compare(ListNode node1, ListNode node2) {
                return node1.val - node2.val;
            }
        });

        ListNode dummy = new ListNode();

        ListNode tail = dummy;
        for(int i = 0; i < nodeList.size(); i++) {
            tail.next = nodeList.get(i);
            tail = tail.next;
            System.out.print(tail.val);
        }
        tail.next = null;
        return dummy.next;

方法三:自顶向下归并排序

class Solution {
    public ListNode sortList(ListNode head) {
        return sortList(head, null);
    }

    public ListNode sortList(ListNode head, ListNode tail) {
        if (head == null) {
            return head;
        }
        if (head.next == tail) {
            head.next = null;
            return head;
        }

        ListNode slow = head;
        ListNode fast = head;
        while (fast != tail) {
            slow = slow.next;
            fast = fast.next;
            if (fast != tail) {
                fast = fast.next;
            }
        }
        ListNode mid = slow;
        ListNode list1 = sortList(head, mid);
        ListNode list2 = sortList(mid, tail);
        ListNode sorted = merge(list1, list2);
        return sorted;
    }
    
    public ListNode merge(ListNode head1, ListNode head2) {
        ListNode dummyHead = new ListNode(0);
        ListNode temp = dummyHead, temp1 = head1, temp2 = head2;
        while (temp1 != null && temp2 != null) {
            if (temp1.val <= temp2.val) {
                temp.next = temp1;
                temp1 = temp1.next;
            } else {
                temp.next = temp2;
                temp2 = temp2.next;
            }
            temp = temp.next;
        }
        if (temp1 != null) {
            temp.next = temp1;
        } else if (temp2 != null) {
            temp.next = temp2;
        }
        return dummyHead.next;
    }
}
posted on 2025-07-17 11:13  caoshikui  阅读(11)  评论(0)    收藏  举报