题目传送:https://leetcode.cn/problems/sort-list/
运行效率:
代码如下:
class Solution {
public ListNode sortList(ListNode head) {
//处理边界情况
if(head==null||head.next==null){
return head;
}
ArrayList<ListNode> list = new ArrayList<>();
while (head != null) {
list.add(head);
head = head.next;
}
ListNode[] array = list.toArray(new ListNode[0]);
Arrays.sort(array, Comparator.comparingInt(o -> o.val));
for(int i=0;i< array.length-1;i++){
array[i].next=array[i+1];
}
array[array.length-1].next=null; //避免产生环形,把最后一个节点的next指针置为空,
return array[0];
}
}