16.合并两个排序的链表
题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
记录
方法一:
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回合并后列表
def Merge(self, pHead1, pHead2):
#write code here
#常规判空
if pHead1 is None and pHead2 is None:
return None
if pHead1 == None:
return pHead2
if pHead2 == None:
return pHead1
#新链表的起点
new = ListNode(0)
p = new
#寻找两个链表中较小的下一位放在新链表后面
while pHead1 and pHead2:
if pHead1.val <= pHead2.val:
new.next = pHead1
pHead1 = pHead1.next
elif pHead1.val > pHead2.val:
new.next = pHead2
pHead2 = pHead2.next
#到下一个节点开始循环
new = new.next
#将没走完链表剩下的全部放到新链表后面
new.next = pHead1 or pHead2
#p为0,要返回第一个应该是p.next
return p.next
方法二:
递归。和方法一差不多。
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回合并后列表
def Merge(self, pHead1, pHead2):
#write code here
if pHead1 is None and pHead2 is None:
return None
if pHead1 == None:
return pHead2
if pHead2 == None:
return pHead1
while pHead1 and pHead2:
if pHead1.val <= pHead2.val:
pHead1.next = self.Merge(pHead1.next, pHead2)
return pHead1
elif pHead1.val > pHead2.val:
pHead2.next = self.Merge(pHead1, pHead2.next)
return pHead2