题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则
输入输出示例
输入:{1, 3, 5}, {2, 4, 6}
返回值:{1, 2, 3, 4, 5, 6}
解题思路
- 非递归解法
代码示例
- 非递归解法
# coding:utf-8
'''
合并两个有序链表
'''
class Solution:
# 返回合并后列表
def Merge(self, pHead1, pHead2):
# write code here
# 考虑边界值,其中一个链表为空时,直接返回另一个链表
if pHead1 == None:
return pHead2
if pHead2 == None:
return pHead1
# 确定合并后链表的首结点,确定合并后的链表
newHead = pHead1 if pHead1.val < pHead2.val else pHead2
# 定义指针,指向合并后链表的最后一个结点
pre = newHead
if newHead == pHead1:
pHead1 = pHead1.next
if newHead == pHead2:
pHead2 = pHead2.next
# 循环遍历,比较大小,终止条件为任意一个链表为空
while pHead1 and pHead2:
if pHead1.val < pHead2.val:
pre.next = pHead1
# 指针移动
pre = pre.next
pHead1 = pHead1.next
else:
pre.next = pHead2
pre = pre.next
pHead2 = pHead2.next
# 退出循环后,直接追加剩余链表到合并链表中
if pHead1 == None:
pre.next = pHead2
else:
pre.next = pHead1
return newHead
- 递归解法
class Solution:
# 返回合并后列表
def Merge(self, pHead1, pHead2):
# write code here
if pHead1 == None:
return pHead2
if pHead2 == None:
return pHead1
newHead = pHead1 if pHead1.val < pHead2.val else pHead2
pre = newHead
if pHead1.val < pHead2.val:
pre.next = self.MergeDigui(pHead1.next, pHead2)
else:
pre.next = self.MergeDigui(pHead1, pHead2.next)
return newHead