21. 合并两个有序链表

题目

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

示例 1:

输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]

示例 2:

输入:l1 = [], l2 = []
输出:[]

示例 3:

输入:l1 = [], l2 = [0]
输出:[0]

python

双指针

class Solution:
    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
        # 创建一个新的头节点
        new_head = ListNode(0)
        tail = new_head#尾指针

        # 依次比较两个链表的节点,并将较小的节点插入到新链表的尾部
        while list1 !=None and list2!=None:
            if list1.val <= list2.val:
                tail.next = list1#放在新的链表后面
                list1 = list1.next#往后移继续判断
            else:
                tail.next = list2#放在新的链表后面
                list2 = list2.next#往后移继续判断
            tail = tail.next
        # 将剩余的节点直接连接到新链表的尾部
        if list1:#如果list1还没遍历完
            tail.next = list1#直接加在后面
        elif list2:#如果list2还没遍历完
            tail.next = list2#直接加在后面

        return new_head.next

javascript

双指针

  • 双指针,小的加入结果链表(移动当前链表指针和结果链表指针),结束条件是某一个链表结束。把还没结束的链表全部加入结果链表
var mergeTwoLists = function(list1, list2) {
    let a = list1, b = list2
    let result = new ListNode(0)
    let c = result
    while(a && b){
        if(a.val<= b.val){
            c.next = a
            a=a.next
            c = c.next
        }
        else{
            c.next = b
            b = b.next
            c = c.next
        }
    }
    if(a){
        c.next = a
    }
    if(b){
        c.next = b
    }
    return result.next
};
posted @   Frommoon  阅读(7)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
点击右上角即可分享
微信分享提示