Skip to content

Latest commit

 

History

History
74 lines (71 loc) · 1.58 KB

21. 合并两个有序链表.md

File metadata and controls

74 lines (71 loc) · 1.58 KB

将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 

示例:

输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4

solution:

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var mergeTwoLists = function (l1, l2) {
  function listNode(val) {
    this.val = val;
    this.next = null;
  }

  function fillNode(nodeList, val) {
    if (nodeList.next === null) {
      nodeList.next = {
        val: val,
        next: null
      }
    } else {
      return fillNode(nodeList.next, val)
    }
  }
  if (l1 === null && l2 === null) {
    return null
  } else if (l1 === null) {
    return l2
  } else if (l2 === null) {
    return l1
  } else {
    var pre = l1,
      aft = l2
    var result
    if (pre.val < aft.val) {
      result = new listNode(pre.val)
      pre = pre.next
    } else {
      result = new listNode(aft.val)
      aft = aft.next
    }
    while (pre !== null || aft !== null) {
      if (pre !== null && aft !== null && pre.val < aft.val) {
        fillNode(result, pre.val)
        pre = pre.next
      } else if (pre !== null && aft !== null && pre.val >= aft.val) {
        fillNode(result, aft.val)
        aft = aft.next
      } else if (pre === null) {
        fillNode(result, aft.val)
        aft = aft.next
      } else {
        fillNode(result, pre.val)
        pre = pre.next
      }
    }
    return result
  }
};