输入两个递增的链表,单个链表的长度为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}:
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param pHead1 ListNode类
# @param pHead2 ListNode类
# @return ListNode类
#
class Solution:
def Merge(self , pHead1: ListNode, pHead2: ListNode) -> ListNode:
myhead = None
cur = None
if not pHead1:
return pHead2
elif not pHead2:
return pHead1
#1. 大循环把phead1, phead2一个给循环完
while pHead1 is not None and pHead2 is not None:
if pHead1.val < pHead2.val:
tmp = pHead1.next
pHead1.next = None
if cur:
cur.next = pHead1
cur = cur.next
else:
cur = pHead1
myhead = cur
pHead1 = tmp
else:
tmp = pHead2.next
pHead2.next = None
if cur:
cur.next = pHead2
cur = cur.next
else:
cur = pHead2
myhead = cur
pHead2 = tmp
#2. 接下来只要把非空那个列表的所有结点都放到后面即可。
if pHead1:
cur.next = pHead1
if pHead2:
cur.next = pHead2
return myhead
# write code here
评价:
- 代码过于冗长,可以消除第一段循环,并且对于后面拼接的代码也不够间接。
优化步骤
- 对于一开始是否为空的判断,以及空的初始化,可以借用re = listNode(0)来初始化一个链表头,这时候就具有了next的指针,这样的好处是消除了第一个 “if cur:” 对cur是否是空的判断。只需要在最终返回的时候饭回re.next即可。
v2:
class Solution:
def Merge(self , pHead1: ListNode, pHead2: ListNode) -> ListNode:
myhead = ListNode(0)
cur = myhead
#1. 大循环把phead1, phead2一个给循环完
while pHead1 and pHead2:
if pHead1.val < pHead2.val:
tmp = pHead1.next
pHead1.next = None #YY:可以省略
cur.next = pHead1
cur = cur.next
pHead1 = tmp #若省略YY,则可以简写为pHead1=pHead1.next,不需要tmp
else:
tmp = pHead2.next
pHead2.next = None
cur.next = pHead2
cur = cur.next
pHead2 = tmp
#2. 接下来只要把非空那个列表的所有结点都放到后面即可。
if pHead1:
cur.next = pHead1
if pHead2:
cur.next = pHead2
return myhead.next