Leetcode日练笔记33 [linked list专题] #21 #2 Merge Two Sorted Lists & Add Two Numbers

#21 Merge Two Sorted Lists

You are given the heads of two sorted linked lists list1 and list2.

Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.

Return the head of the merged linked list.

解题思路:

分两种,一个是iterative的,另外一个是recursive的。后者的time 和 space complexity都是O(m+n)。前者time complexity是O(m+n),space complexity是O(1)【这里暂时不明白】。

iterative的方法是先排除两个list没有节点的情况,然后比较两个list排头的val大小,小的放入新的list中,然后继续比较后续的节点,直到其中一个list没有节点为止,就把另外一个list剩下的节点接在新list的后面。新的list操作时需要两个pointers,一个是记录整个list,head。另外一个是接最小值用的,tail。

# rule out the possibility of either list1 or list2 is None
        if not list1:
            if not list2:
                return None
            else:
                return list2
        else:
            if not list2:
                return list1
        
        # create a new linked list
        head = ListNode(0)
        
        # attach the smallest nodes from two linked lists to the new one
        while list1 and list2:
            if list1.val <= list2.val:
                # the first node attached to head
                if not head.next:
                    head.next = list1
                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值