[leetcode] 147. Insertion Sort List (Medium)

版权声明:by ruohua3kou https://blog.csdn.net/ruohua3kou/article/details/82996774

原题

别人的思路 非常简洁


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;
};

猜你喜欢

转载自blog.csdn.net/ruohua3kou/article/details/82996774