链表排序
在O(n log n)的时间内使用常数级空间复杂度对链表进行排序。
{30,20,40} => {20,30,40}
/* * function ListNode(x){ * this.val = x; * this.next = null; * } */ /** * * @param head ListNode类 * @return ListNode类 */ function sortList( head ) { // write code here if(head==null || head.next==null) { return head; } var arr = []; var current = head while(current){ arr.push(current.val) current = current.next } arr.sort(function(a,b){return a-b;}) var newhead = new ListNode(0) var cur = newhead for(var i=0;i<arr.length;i++){ var node = new ListNode(arr[i]) cur.next = node cur = cur.next } return newhead.next } module.exports = { sortList : sortList };
链表算法 文章被收录于专栏
链表相关算法