LeetCode 21. 合并两个有序链表

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

在这里插入图片描述
代码:

function ListNode(val, next) {
  this.val = (val === undefined ? 0 : val)
  this.next = (next === undefined ? null : next)
}

let mergeTwoLists = function(list1, list2) {
  let preHead = new ListNode(0) // 预设一个头的前缀结点,用于拼接两个链表
  
  let node = preHead // 当前生成链表的尾结点
  
  while(list1 !== null && list2 !== null) {
  	// 每次将list1与list2中小的插入生成链表的尾结点后面,并令操作位置往后移一位
      if(list1.val <= list2.val) {
          node.next = list1
          list1 = list1.node
      }
      else {
          node.next = list2
          list2 = list2.next
      }
      
      // 尾结点更新
      node = node.next
  }
  // 当某个链表走到最后,其中另一个链表后半部分结点可能未插入,因此,将其直接接到尾结点后面
  node.next = list1 === null ? list2 : list1
  
  // 返回预设结点的后一位
  return preHead.next
};

let list1 = new ListNode(1, new ListNode(3, new ListNode(4)))
let list2 = new ListNode(2, new ListNode(2, new ListNode(2)))

let res = mergeTwoLists(list1, list2)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值