BM12 单链表的排序
描述
给定一个节点数为 n 的无序单链表,对其按升序排序。
数据范围:0<n≤1000000<n≤100000,保证节点权值在[−109,109][−109,109]之内。
要求:空间复杂度 O(n)O(n),时间复杂度 O(nlogn)O(nlogn)
示例 1
输入:
[1,3,2,4,5]
返回值:
{1,2,3,4,5}
示例 2
输入:
[-1,0,-2]
返回值:
{-2,-1,0}
题解
转换为数组排序
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) {
// write code here
List<Integer> list = new ArrayList<>();
while (head != null) {
list.add(head.val);
head = head.next;
}
Collections.sort(list);
ListNode res = new ListNode(-1);
ListNode cur = res;
for (int i = 0; i < list.size(); i++) {
ListNode node = new ListNode(list.get(i));
cur.next = node;
cur = cur.next;
}
return res.next;
}
}