描述
给定一个节点数为n的无序单链表,对其按升序排序。
数据范围:0 < n \le 1000000<n≤100000
要求:时间复杂度 O(nlogn)O(nlogn)
示例1
输入:
{1,3,2,4,5}
返回值:
{1,2,3,4,5}
示例2
输入:
{-1,0,-2}
返回值:
{-2,-1,0};
思路:这题还是简单,先取值保存到数组里然后直接使用数组的sort方法,在将排序好的值放回去即可;
代码
function ListNode(x){
this.val = x;
this.next = null;
}
/**
*
* @param head ListNode类 the head node
* @return ListNode类
*/
function sortInList( head ) {
// write code here
let arr = [], obj = head, temp = null;
if(!head || !head.next) return head;
while(head){
arr.push(head.val);
head = head.next;
}
arr.sort((a, b) => a - b);
temp = obj;
for( let i = 0; i < arr.length; i++){
temp.val = arr[i];
temp = temp .next;
}
return obj;
}
module.exports = {
sortInList : sortInList
};
来自牛客编程题 https://www.nowcoder.com/exam/oj