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

python实现链表的反转

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

python实现链表的反转

python里面是没有链表这个概念的,所以我们需要自己构造一个链表,然后再实现链表的反转;

这是老师上课讲的图解,仅供参考,应该是看不懂的

具体代码实现

"""
@version:
@filename : 链表反转
@author : liuhongjie
@projectname: day02
@time: 2022/05/30
"""

#定义一个节点类,用来等一下实现链表的创建
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    #实现链表的反转
    def reverseList(self, head):
        pre, cur = None, head
        while cur:
            tmp = cur.next
            cur.next = pre
            pre = cur
            cur = tmp
        return pre

#把反转以后的链表打印出来
def print_linked_list(head):
    if not head or not head.next:
        return []
    result = []
    while head:
        result.append(head.val)
        head = head.next
    return result

# 调用节点类,创建一个链表: a->b->c,分别对应的就是:1,2,3
a = ListNode(1)
b = ListNode(2)
c = ListNode(3)
a.next = b
b.next = c
#创建一个实例化对象
demo = Solution()
print(print_linked_list(demo.reverseList(a)))


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

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

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