题目
思路一:
两个链表从头开始对比l1.val
和l2.val
的值,选出值较小的结点的next
指向其余节点的合并结果。(递归)
解法一:
#定义链表的结点
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
#通过输入的列表来生成链表
def generateList(l: list):
prenode = ListNode(0)
lastnode = prenode
for val in l:
lastnode.next = ListNode(val)
lastnode = lastnode.next
return prenode.next #返回链表头结点(同个结点出发的.next相同)
#打印链表
def printList(l: ListNode):
while l:
print("%d, " % (l.val), end='')
l = l.next
print('')
class Solution:
def mergeTwoLists(self,l1: ListNode, l2: ListNode) -> ListNode:
# 终止条件,直到两个链表都空
if not l1:
return l2
if not l2:
return l1
if l1.val <= l2.val: # 递归调用
l1.next = self.mergeTwoLists(l1.next, l2)
return l1
else:
l2.next = self.mergeTwoLists(l1, l2.next)
return l2
list_a = [1,2,5,7]
list_b = [1,3,4,9]
l1 = generateList(list_a) #生成链表
l2 = generateList(list_b)
printList(l1)
printList(l2)
s = Solution()
print(s.mergeTwoLists(l1,l2))
思路二:
设置一个新的链表,对比两个链表的对应位置值的大小,较小的输入新链表中,依次类推。构造链表的方法与解法一中相同,这里解法只写出函数部分。
解法二:
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
p1 = l1
p2 = l2
newList = ListNode(None)
pn = newList
while p1 and p2:
if p1.val <= p2.val:
newNode = ListNode(p1.val)
pn.next = newNode
pn = pn.next
p1 = p1.next
else:
newNode = ListNode(p2.val)
pn.next = newNode
pn = pn.next
p2 = p2.next
if p1 and p2==None:
pn.next = p1
if p2 and p1==None:
pn.next = p2
return newList.next