合并两个已经排好序的链表,注意需要用已有的节点组成新链表。这题与第4题很相似。

合并两个数组如下

    var newArray = []
    function merge(el) {
      newArray.push(el)
    }

    while (true) {
      if (nums1[a] < nums2[b]) {
        merge(nums1[a])
        a++
        continue
      }
      if (nums2[b] < nums1[a]) {
        merge(nums2[b])
        b++
        continue
      }
      if (a < nums1.length) {
        merge(nums1[a])
        a++
        continue
      }
      if (b < nums2.length) {
        merge(nums2[b])
        b++
        continue
      }
      return newArray
    }

合并两个链表差不多

var mergeTwoLists = function(l1, l2) {
    var dummy = new ListNode, node = dummy
    while(true){
      if (l1 && l2){
         if (l1.val <= l2.val) {
            node = node.next = l1;
            l1 = l1.next
          } else {
            node = node.next = l2;
            l2 = l2.next
          }
          continue
      }
      if(!l2 && l1){
          node =  node.next = l1
          l1 = l1.next
           continue
      }
      if(!l1 && l2){
          node =  node.next = l2
          l2 = l2.next
           continue
      }
      return dummy.next
      
  }
  return dummy.next
    
};

相关文章:

  • 2021-11-05
  • 2022-01-16
  • 2021-09-10
  • 2021-11-24
  • 2021-08-22
  • 2022-02-07
  • 2021-05-26
猜你喜欢
  • 2021-08-18
  • 2022-01-14
  • 2021-05-26
  • 2021-10-01
  • 2021-06-02
  • 2021-05-22
  • 2022-01-02
相关资源
相似解决方案