[leetcode] 147. Insertion Sort List (Medium)

原题

别人的思路 非常简洁


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;
};
posted @ 2018-10-10 14:39  Ruohua3kou  阅读(120)  评论(0编辑  收藏  举报