首页 > 编程语言 >【Python】python实现双向链表

【Python】python实现双向链表

时间:2024-06-18 17:28:19浏览次数:13  
标签:current head Python self next 链表 python prev data

一、定义与结构

双向链表(Doubly Linked List)是一种链式数据结构,每个节点(Node)包含三个部分:一个数据域(data),一个指向前驱节点的指针(prev),以及一个指向后继节点的指针(next)。双向链表的每个节点都链接到前一个节点和后一个节点,从而允许在两个方向上进行遍历。
双向链表的结构

+------+-----+------+       +------+-----+------+       +------+-----+------+
| prev |     | next | ----> | prev |     | next | ----> | prev |     | next |
+------+-----+------+       +------+-----+------+       +------+-----+------+

prev:指向前一个节点的指针。如果是头节点(head),则 prev 为 nil 或 None。
data:存储的数据。
next:指向下一个节点的指针。如果是尾节点(tail),则 next 为 nil 或 None。

二、特点与场景

特点
双向遍历:可以从头到尾遍历,也可以从尾到头遍历。
插入和删除操作:在已知位置进行插入和删除操作的时间复杂度为 O(1),因为不需要像数组那样进行大量元素的移动。
优点
相比单向链表,双向链表可以方便地进行反向遍历和操作。
插入和删除操作较为高效。
缺点
每个节点需要额外的空间来存储两个指针(prev 和 next)。
操作时需要维护两个指针,逻辑稍复杂。
使用场景
需要频繁插入和删除操作的场景。
需要在链表中从任意位置进行高效的前向和后向遍历的场景。

三、Python代码实现

定义节点结构

class Node:

    def __init__(self, data=None):
        self.data = data
        self.next = None
        self.prev = None

定义链表与方法

class DLinkedList:

    def __init__(self):
        self.head = None
    
    def append(self, data):
        if not self.head:
            self.head = Node(data)
        else:
            new_node = Node(data)
            current = self.head
            while current.next:
                current = current.next
            current.next = new_node
            new_node.prev = current

    def prepend(self, data):
        new_node = Node(data)
        if not self.head:
            self.head = new_node
        else:
            new_node.next = self.head
            self.head.prev = new_node
            self.head = new_node

    def move_to_front(self, key):
        ## 将元素移到头(为了实现lru算法而实现的方法)
        if not self.head:
            return
        current = self.head
        while current:
            if current.data == key:
                if current.prev is None:
                    return
                
                if current.prev:
                    current.prev.next = current.next

                if current.next:
                    current.next.prev = current.prev

                current.next = self.head
                current.prev = None
                self.head.prev = current
                self.head = current
                return
            current = current.next

    def back(self):
        # 删除最后一个元素
        if not self.head:
            return
        if self.head.next is None:
            self.head = None
            return
        current = self.head
        while current:
            current = current.next
        if current.prev:
            current.prev = None
        return current
        
    def display(self):
        data = []
        if self.head:
            current = self.head
            while current:
                data.append(current.data)
                current = current.next

        print(data)

测试

dl = DLinkedList()
dl.append(1)
dl.display()
dl.prepend(2)
dl.display()
dl.append(3)
dl.display()
dl.prepend(4)
dl.display()
dl.move_to_front(1)
dl.display()

结果

[1]
[2, 1]
[2, 1, 3]
[4, 2, 1, 3]
[1, 4, 2, 3]

标签:current,head,Python,self,next,链表,python,prev,data
From: https://blog.csdn.net/qq_40375355/article/details/139776474

相关文章

  • 自动化之python读取目录结构转换为element-plus tree结构
    defget_project_tree(start_path:str,original_path:str,tree_data:list):child_files=os.listdir(start_path)forchild_fileinchild_files:ifchild_filein['.gitignore','.idea','venv','__pycache__......
  • Python - Arrays and Numpy Arrays
    Mostprogramminglanguagesprovideadatastructurecalledarrays.InPython,arrayisapackageanditisdifferentfrom“core”pythonlists.    Thesyntaxforcreatinganarray. DifferencesbetweenNumpyArraysandArrays PythonPredefi......
  • k8s的python客户端库--kubernetes
    简介Kubernetes是什么Kubernetes是一个全新的基于容器技术的分布式架构解决方案,是Google开源的一个容器集群管理系统,Kubernetes简称K8S。Kubernetes是一个一站式的完备的分布式系统开发和支撑平台,更是一个开放平台,对现有的编程语言、编程框架、中间件没有任何侵入性。K......
  • python简单账表(包括联查)
    import clrclr.AddReference("System")clr.AddReference("Kingdee.BOS")clr.AddReference("Kingdee.BOS.Core")clr.AddReference("Kingdee.BOS.DataEntity")clr.AddReference("Kingdee.BOS.App")clr.AddReference(&q......
  • 关于几种语言(c#,php,python,javascript)字符串的gzip压缩与解压的整理
    背景介绍因为一直在处理restfulAPI,给移动端提供的数据需要考虑流量问题,优先考虑就是压缩现有的字符串,然后再考虑业务逻辑方面的减少流量。鉴于找这些资料也花了不少时间,所以整理了这篇文章,留作纪念。参考网址PHP与C#的压缩与解压http://www.oschina.net/question/2265205_181......
  • python函数声明(参数/返回值注释)和三个双引号用法
     1#python的"""三个双引号两种用法:(1)多行注释(2)定义多行字符串2deff1(ham:42,eggs:int='spam')->"Nothingtoseehere":3print("函数注释",f1.__annotations__)#函数注释{'ham':42,'eggs':<cl......
  • (slam工具)6 python四元数转化旋转矩阵
       importnumpyasnpfromscipy.spatial.transformimportRotationasRimportpyprojfrompyprojimportProj,transform#0.0169380355232107080.58455146147157355-0.488705791564092830.64744060819180593-129342.747563395343469822.8668770161534369......
  • IPython 使用技巧整理
    IPython使用技巧整理IPython是一种强大的交互式Pythonshell,提供了许多增强功能,适合数据科学、机器学习和科学计算等多个领域。以下是一些常用的IPython使用技巧。目录基础功能魔法命令扩展和插件与JupyterNotebook的集成调试与错误处理性能优化基础功能1.自动......
  • 小于n的最大数 - 贪心算法及证明 - 附python实现
    一、问题描述?    给定一个整数n,并从1~9中给定若干个可以使用的数字,根据上述两个条件,得到每一位都为给定可使用数字的、最大的小于整数n的数。    例如,给定可以使用的数字为{2,3,8}三个数:    给定n=3589,输出3388;给定n=8234,输出8233;…… 二、解......
  • Python - Meta Class
    Aspartofmetaprogramming,ametaclassisoneofthemostimportantconceptsinPython.AClassinPythondefinesthefunctionalityofitsobjectsusingattributesandmethods.Incontrast,ametaclassdefinesthefunctionalityoftheclasses,whereast......