美文网首页剑指offer- python实现
面试题25:合并两个排序的链表

面试题25:合并两个排序的链表

作者: 不会编程的程序猿甲 | 来源:发表于2020-03-09 15:13 被阅读0次

题目:
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。

解题思路:
这道题符合递归的套路,因为每一步和上一步的操作相同,还要注意其中一个为空的特殊情况,具体思路如下:

25 合并两个排序的链表.png

代码实现:

# -*- 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 == None:
           return pHead2
       if pHead2 == None:
           return pHead1
       combine = None
       if(pHead1.val < pHead2.val):    #比较节点的大小值
           combine = pHead1
           combine.next = self.Merge(pHead1.next,pHead2)
       else:
           combine = pHead2
           combine.next = self.Merge(pHead1,pHead2.next)
       return combine

提交结果:

牛客网提交结果

相关文章

网友评论

    本文标题:面试题25:合并两个排序的链表

    本文链接:https://www.haomeiwen.com/subject/heqpdhtx.html