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

两两交换链表 python

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

两两交换链表 python

怎么说,,,迭代的时候一定要注意首和尾。不然就会无限循环

1、迭代

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

l1 = ListNode(1)
head = l1
for i in range(2, 9):
    head.next = ListNode(i)
    head = head.next
head = l1
# 迭代
dunmmy = ListNode(0)
dunmmy.next = head
pre = head
cur = head
a = dunmmy
while cur and cur.next:
    cur = cur.next
    a.next = cur
    t = cur.next
    cur.next = pre
    a = pre
    pre = t
    cur = pre
a.next = cur  # 防止无限循环
head = dunmmy.next
while head != None:
    print(head.val)
    head = head.next

2、递归,要注意当两个参数出界时,可以换成一个参数啊,就不用这么多限制了

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

l1 = ListNode(1)
head = l1
for i in range(2, 9):
    head.next = ListNode(i)
    head = head.next
head = l1
#递归
def chang2(pre, cur):
    if pre == None or cur == None:
        return pre
    t = cur.next
    cur.next = pre
    if t == None:
        return None
    pre.next = chang2(t, t.next)
    return cur

head = chang2(head, head.next)
while head != None:
    print(head.val)
    head = head.next

还是应该多看看参考答案,找找差距,,

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

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

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