常规解法1
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if not (l1 and l2):
return l1 if l1 else l2
p = r =ListNode(None) ## 新建节点和指针
while True:
try:
while l1.val<=l2.val: ## 若l1更小,`p.next`就指向l1,同时更新l1,p节点
p.next = l1
l1, p = l1.next, p.next
while l1.val>l2.val: ## 若l2更小,`p.next`就指向l2,同时更新l2,p节点
p.next = l2
l2, p = l2.next, p.next
except:break ## 发生异常时,一定l1/l2至少一个为None了
p.next = l1 or l2 ## 接上不为None的节点
return r.next
常规解法2
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
p = h = ListNode(None)
while l1 and l2:
if l1.val <= l2.val:
p.next = l1
l1 = l1.next
else:
p.next = l2
l2 = l2.next
p = p.next
p.next = l1 if l1 else l2
return h.next
递归解法
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if not (l1 and l2):
return l1 if l1 else l2
if l1.val <= l2.val:
l1.next = Solution().mergeTwoLists(l1.next,l2)
return l1
else:
l2.next = Solution().mergeTwoLists(l1,l2.next)
return l2
写个测试代码
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def initList(self, data):
# 判断是否为空
if len(data) == 0:
return
else:
# 创建头结点
self.head = ListNode(data[0])
r = self.head
p = self.head
# 逐个为 data 内的数据创建结点, 建立链表
for i in data[1:]:
node = ListNode(i)
p.next = node
p = p.next
return r
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if not (l1 and l2):
return l1 if l1 else l2
if l1.val <= l2.val:
l1.next = Solution().mergeTwoLists(l1.next,l2)
return l1
else:
l2.next = Solution().mergeTwoLists(l1,l2.next)
return l2
def listnode_result(self, ListNode):
while ListNode:
print(ListNode.val, end='')
ListNode = ListNode.next
if ListNode:
print('->', end='')
if __name__ == "__main__":
test = Solution()
data1 = [1, 2, 4]
data2 = [1, 3, 4]
l1 = test.initList(data1)
print(l1.val, "->", l1.next.val, "->", l1.next.next.val)
l2 = test.initList(data2)
print(l2.val, "->", l2.next.val, "->", l2.next.next.val)
result = test.mergeTwoLists(l1, l2)
result = test.listnode_result(result)