21. Merge Two Sorted Lists

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

 

 1 # Definition for singly-linked list.
 2 # class ListNode(object):
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.next = None
 6 
 7 class Solution(object):
 8     def mergeTwoLists(self, l1, l2):
 9         """
10         :type l1: ListNode
11         :type l2: ListNode
12         :rtype: ListNode
13         """
14         def mergeTwoLists(self, a, b):
15             if a and b:
16                 if a.val > b.val:
17                     a, b = b, a
18                 a.next = self.mergeTwoLists(a.next, b)
19             return a or b

上面程序Failed掉了。

when a=[],b=[0], return [].

但是在IDLE上面看,when a=[],b=[0], a or b = [0].

 

 1 # Definition for singly-linked list.
 2 # class ListNode(object):
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.next = None
 6 
 7 class Solution(object):
 8     def mergeTwoLists(self, l1, l2):
 9         """
10         :type l1: ListNode
11         :type l2: ListNode
12         :rtype: ListNode
13         """
14         dummyHead = ListNode(None)
15         curNode   = dummyHead
16         while True:
17             # When one node becomes empty
18             if not l1:
19                 curNode.next = l2
20                 l2 = None
21                 break
22             if not l2:
23                 curNode.next = l1
24                 l1 = None
25                 break
26             
27             if l1.val > l2.val:
28                 curNode.next = l2
29                 l2 = l2.next
30             else:
31                 curNode.next = l1
32                 l1 = l1.next
33             curNode = curNode.next
34         return dummyHead.next

dummyHead当存储的列表,curNode当索引。

转载于:https://www.cnblogs.com/fullest-life/p/6529377.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值