[leetcode] 147. Insertion Sort List (Medium)

时间:2021-06-26 21:03:51

原题

别人的思路 非常简洁


function ListNode(val) {
this.val = val;
this.next = null;
} /**
* @param {ListNode} head
* @return {ListNode}
*/
var insertionSortList = function(head) {
if (head === null) {
return head;
}
var helper = new ListNode(0);
var cur = head.next;
var pre = helper;
var next = null;
while (cur != null) {
next = cur.next;
while (pre.next != null && pre.next.val < cur.val) {
pre = pre.next;
}
cur.next = pre.next;
pre.next = cur;
pre = helper;
cur = next;
}
return helper.next;
};