# -*- 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
#方案2 把结果用列表存放再返回用递归方法,不断进行比较合并返回
if not pHead1:
return pHead2
if not pHead2:
return pHead1
res = None
if pHead1.val < pHead2.val:
res = pHead1
res.next = self.Merge(pHead1.next,pHead2)
else:
res = pHead2
res.next = self.Merge(pHead1, pHead2.next)
return res
#方案1 把链表里的数据放出来装到list里再排序,再装回一个新链表
if pHead1 == None and pHead2 == None:
return pHead1 or pHead2
else:
stack1 = []
stack2 = []
stack = []
res = ListNode(0)
dummy = res
while pHead1:
stack1.append(pHead1.val)
pHead1 = pHead1.next
while pHead2:
stack2.append(pHead2.val)
pHead2 = pHead2.next
stack = sorted(stack1 + stack2) #用sort()和sorted()来排序,注意sort()没返回值, sorted()有返回值,
for i in stack:
dummy.next = ListNode(i)
dummy = dummy.next
return res.next
牛课力扣---NC33 合并两个排序的链表
最新推荐文章于 2024-07-12 19:30:19 发布