33.排序链表

给你链表的头结点 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 = []
输出:[]

提示:

  • 链表中节点的数目在范围 [0, 5 * 104] 内
  • -105 <= Node.val <= 105

代码:

/**
 * 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) {
        //定义一个列表用于存储链表元素
        List<Integer>list = new ArrayList<>();
        //定义节点指向当前头节点
        ListNode cur = head; 
        //如果当前节点不为空,就继续遍历该链表
        while(cur!=null){
            //将当前节点的值存入列表
            list.add(cur.val);
            //当前节点往后移动
            cur = cur.next;
        }
        //将列表元素按照从小到大排序
        Collections.sort(list);
        //将cur指向头节点以便下一次遍历
        cur = head;
        //cnt为下标
        int cnt=0;
        //如果当前节点不为空,就继续遍历该链表
        while(cur!=null){
            //将链表当前节点的值重新设置为列表当前值,列表cnt++
            cur.val = list.get(cnt++);
            //当前节点往后移动
            cur = cur.next;
        }
        //返回链表头节点
        return head;
    }
}
posted @ 2025-04-24 10:04  回忆、少年  阅读(8)  评论(0)    收藏  举报