import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类 the head node
* @return ListNode类
*/
public ListNode sortInList (ListNode head) {
if (head == null || head.next == null) return head;
// write code here
List<Integer> list = new LinkedList<>();
ListNode p = head;
while (p != null) {
list.add(p.val);
p = p.next;
}
Collections.sort(list);
ListNode dummyHead = new ListNode(0); // 虚拟头节点
ListNode pCurrent = dummyHead;
for (int val : list) {
pCurrent.next = new ListNode(val);
pCurrent = pCurrent.next;
}
// 返回排序后链表的真实头节点(跳过虚拟头节点)
return dummyHead.next;
}
}
单链表的排序
最新推荐文章于 2024-06-19 18:43:14 发布