题目描述:
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
方法一:双指针(三指针)
class ListNode: # 单链表的结点
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if l1 is None:
return l2
if l2 is None:
return l1
# 头结点 value = -1
prehead = ListNode(-1)
p = prehead
# l1 和 l2 都还没取完时 1)比较 2)移动指针p 3)移动指针l
while l1 is not None and l2 is not None:
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 is not None else l2
# 返回不带头指针的链表
return prehead.next
看到leetcode有人问:如何在编译器内写测试类呢?只需要注意两件事:其一,输入一定是链表形式,因此要自建链表;其二,输出可以用遍历的方式验证结果的正确性。
class Test:
def Test(self):
# [1,2,4]
l1 = ListNode(1)
temp1 = l1
temp1.next = ListNode(2)
temp1 = temp1.next
temp1.next = ListNode(4)
temp1 = temp1.next
# [1,2,3]
l2 = ListNode(1)
temp2 = l2
temp2.next = ListNode(2)
temp2 = temp2.next
temp2.next = ListNode(3)
temp2 = temp2.next
s = Solution()
# phead2 = phead.next 哑节点的next
phead2 = s.mergeTwoLists(l1,l2)
while phead2 != None:
print(phead2.val, end='→')
phead2 = phead2.next
t = Test()
t.Test()
方法二:递归
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if l1 is None:
return l2
if l2 is None:
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
为什么不用单独写一个列表已经被取完的情况呢?
请设想,假设l1在递归第n次时被取完(l1.val < l2.val), l1.next = None,则 进入下一次递归时,
if l1 is None:
return l2
递归结束,l2加在了已形成的链表之后。