合并两个排序的链表
描述
输入两个递增的链表,单个链表的长度为n,合并这两个链表并使新链表中的节点仍然是递增排序的。
数据范围: 0 \le n \le 10000≤n≤1000,-1000 \le 节点值 \le 1000−1000≤节点值≤1000
要求:空间复杂度 O(1)O(1),时间复杂度 O(n)O(n)
如输入{1,3,5},{2,4,6}时,合并后的链表为{1,2,3,4,5,6},所以对应的输出为{1,2,3,4,5,6}
解决方案
合并两个排序的链表,首先这个链表是递增的,那么意味着越到后面越大
做一个新链表,用来放这两个链表合并后的结果
从两个链表里面每次都取出一个值,放一个然后在进行下一个即可
1.0 错误版本
def Merge(self , pHead1: ListNode, pHead2: ListNode) -> ListNode:
# write code here
if pHead1 == None and pHead2 == None:
return None
flag = True
pre = ListNode
while flag:
p = pHead1
q = pHead2
if p.next != None and q.next != None:
if p.val < q.val:
temp = p
p = p.next
pre = temp
else:
temp = q
q = q.next
pre = q
else:
flag = False
return pre
正确版
def Merge(self , pHead1: ListNode, pHead2: ListNode) -> ListNode:
# write code here
pre = ListNode(0) # 新建节点
pHead = pre # 指定头节点
# 如果两个链表不为空,执行循环
while pHead1 and pHead2:
if pHead1.val < pHead2.val:
pre.next = pHead1
pHead1 = pHead1.next
else:
pre.next = pHead2
pHead2 = pHead2.next
pre = pre.next
# 如果1空了,取找2
if not pHead1:
pre.next = pHead2
# 如果2空了,去找1
if not pHead2:
pre.next = pHead1
return pHead.next
# 递归实现
class Solution:
def Merge(self, pHead1, pHead2):
# write code here
if pHead1 is None:
return pHead2
if pHead2 is None:
return pHead1
if pHead1.val < pHead2.val:
#
pHead1.next = self.Merge(pHead1.next,pHead2)
return pHead1
else:
pHead2.next = self.Merge(pHead1,pHead2.next)
return pHead2
问题
为什么递归可以直接输出,难道做了不可描述的事情?