就是归并的思路,只不过换成链表的储存方式罢了。
我的代码:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
if not list1: # 链表1为空的特殊情况:直接返回链表2
return list2
if not list2: # 链表2为空的特殊情况:直接返回链表1
return list1
ptr1 = list1
ptr2 = list2
dummy = ListNode() # 新建链表的头指针的前驱结点
pre = dummy # 记录前一个结点,方便入链表
while ptr1 and ptr2:
if ptr1.val < ptr2.val:
cur = ListNode(ptr1.val) # 新建结点
pre.next = cur # 入链表
pre = pre.next # 指针后移,此时相当于pre = cur
ptr1 = ptr1.next # 扫描指针后移
else:
cur = ListNode(ptr2.val)
pre.next = cur
pre = pre.next
ptr2 = ptr2.next
if not ptr1:
pre.next = ptr2 # 入链表
if not ptr2:
pre.next = ptr1 # 入链表
return dummy.next
看了官方解析用的递归和迭代。递归的代码简洁:
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if l1 is None:
return l2
elif l2 is None:
return l1
elif l1.val < l2.val:
l1.next = self.mergeTwoLists(l1.next, l2)
return l1
else:
l2.next = self.mergeTwoLists(l1, l2.next)
return l2
而迭代的空间复杂度为常数,在本地上修改next指向就成。递归主要是要用到栈,栈空间的大小取决于递归调用的深度,为m+n。
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
prehead = ListNode(-1)
prev = prehead
while l1 and l2:
if l1.val <= l2.val:
prev.next = l1
l1 = l1.next
else:
prev.next = l2
l2 = l2.next
prev = prev.next
# 合并后 l1 和 l2 最多只有一个还未被合并完,我们直接将链表末尾指向未合并完的链表即可
prev.next = l1 if l1 is not None else l2
return prehead.next
但是…