21. Merge Two Sorted Lists

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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当索引。

以上是关于21. Merge Two Sorted Lists的主要内容,如果未能解决你的问题,请参考以下文章

21. Merge Two Sorted Lists

[LeetCode] 21. Merge Two Sorted Lists_Easy tag: Linked List

LeetCode(21) - Merge Two Sorted Lists

21. Merge Two Sorted Lists

21. Merge Two Sorted Lists

LintCode - Merge Two Sorted List