题目
给定一个节点数为n的无序单链表,对其按升序排序。
数据范围:0 < n \le 1000000<n≤100000
要求:空间复杂度 O(n)O(n),时间复杂度 O(nlogn)O(nlogn)
解析
方法有很多种,可以对链表排序,这个有难度,还可以对链表的值排序
对值内容排序,再分别赋给
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类 the head node
* @return ListNode类
*/
public ListNode sortInList (ListNode head) {
// write code here
ArrayList<Integer> list = new ArrayList<>();
ListNode cur = head;
while(cur != null) {
list.add(cur.val);
cur = cur.next;
}
Collections.sort(list);
if(list.size() != 0) {
head.val = list.get(0);
cur = head;
for(int i = 1; i < list.size(); i++) {
cur.next.val = list.get(i);
cur = cur.next;
}
}
return head;
}
}