栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

合并有序链表 python

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

合并有序链表 python

问,卡在哪里,,,竟然卡在我忘了把指针移位,,,而且还要学会 if-else 的写法

pre.next = l2 if l1 is None else l1                                

这是迭代 

class ListNode:
    def __init__(self, x=None, next=None):
        self.val = x
        self.next = None


l1 = ListNode(2)
head = l1
head.next = ListNode(2)
head = head.next
head.next = ListNode(4)

l2 = ListNode(1)
head = l2
head.next = ListNode(3)
head = head.next
head.next = ListNode(4)
dum = ListNode(None)
pre = dum
while l1 and l2:
    if l1.val <= l2.val:
        pre.next = l1
        l1 = l1.next
    else:
        pre.next = l2
        l2 = l2.next
    pre = pre.next
pre.next = l2 if l1 is None else l1
l3 = dum.next
while l3 != None:
    print(l3.val)
    l3 = l3.next

 这是递归,可能找到规律就好写了

class ListNode:
    def __init__(self, x=None, next=None):
        self.val = x
        self.next = None


l1 = ListNode(2)
head = l1
head.next = ListNode(2)
head = head.next
head.next = ListNode(4)

l2 = ListNode(1)
head = l2
head.next = ListNode(3)
head = head.next
head.next = ListNode(4)

# 递归
def pai(l1, l2):
    if l1 == None: return l2
    if l2 == None: return l1
    if l1.val <= l2.val:
        pre = l1
        l1 = l1.next
        pre.next = pai(l1, l2)
    else:
        pre = l2
        l2 = l2.next
        pre.next = pai(l1, l2)
    return pre


head = pai(l1, l2)
while head != None:
    print(head.val)
    head = head.next

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/893458.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号