用Python实现链表

2023-11-18

摘要: 在C/C++语言中,常用结构体+指针来实现链表;而在Python语言中,使用类(class) 来实现链表。

一、创建节点(Node)

链表由多个节点(Node)组成,而每个节点都有两要素组成:
(1)value:该节点的值
(2)next:指向下一个节点

class Node():
    def __init__(self, value):
        self._value = value
        self._next = None

二、创建链表(LinkedList)

创建链表时,链表只有一个参数,就是链表的头部(head),换句话说链表只知道它的头,其余节点只能通过访问其头部来知道。

class LinkedList():
    def __init__(self):
        self._head = None

三、链表的基础成员函数

(1)、is_Empty(): 检查该链表是否为空,为空则返回 True,否则返回 False。
(2)、length(): 返回链表节点的数量
(3)、travel(): 遍历所有节点

class LinkedList():
    def __init__(self, head=None):
        self._head = head

    # judge whether the linkedlist is empty
    def isEmpty(self):
        return self._head == None

    # count the numbers of node of linkedlist
    def length(self):
        if self.isEmpty():
            return 0
        else:
            cur = self._head
            count = 1
            while cur._next != None:
                count += 1
                cur = cur._next
            return count

    # travel all nodes
    def travel(self):
        if self.isEmpty():
            print("The linkedlist is empty!")
        else:
            cur = self._head
            values = []
            while cur != None:
                values.append(cur._value)
                cur = cur._next
            print(values)

四、链表的功能成员函数

(1)、add(): 头部添加节点
(2)、append(): 尾部添加节点
(3)、insert(): 插入节点
(4)、remove(): 删除等于某个值的全部节点
(5)、delete(): 删除某个索引对应的节点
(6)、searchbyvalue(): 根据值返回节点的索引
(7)、searchbyindex(): 根据索引返回节点的值

class LinkedList():
    def __init__(self, head=None):
        self._head = head

    # judge whether the linkedlist is empty
    def isEmpty(self):
        return self._head == None

    # count the numbers of node of linkedlist
    def length(self):
        if self.isEmpty():
            return 0
        else:
            cur = self._head
            count = 1
            while cur._next != None:
                count += 1
                cur = cur._next
            return count

    # travel all nodes
    def travel(self):
        if self.isEmpty():
            print("The linkedlist is empty!")
        else:
            cur = self._head
            values = []
            while cur != None:
                values.append(cur._value)
                cur = cur._next
            print(values)

    # add a node before  the head of linkedlist
    def add(self, value):
        node = Node(value)
        node._next = self._head
        self._head = node

    # add a node in the tail of linkedlist
    def append(self, value):
        node = Node(value)
        if self.isEmpty():
            self._head = node
        else:
            cur = self._head
            while cur._next != None:
                cur = cur._next
            cur._next = node

    # insert a node in the position of linkedlist
    def insert(self, pos, value):
        if pos <= 0:
            self.add(value)
        elif pos > (self.length()-1):
            self.append(value)
        else:
            node = Node(value)
            cur = self._head
            index = 0
            while index < (pos-1):
                index += 1
                cur = cur._next
            node._next = cur._next
            cur._next = node

    # remove all nodes whose value is equal to the input value
    def remove(self, value):
        pre = None
        cur = self._head
        while cur != None:
            if cur._value == value:
                if pre == None:
                    self._head = self._head._next
                    cur = self._head
                    continue
                else:
                    pre._next = cur._next
                    cur = cur._next
                    continue
            pre, cur = cur, cur._next

    # delete a node from linkedlist according to its index
    def delete(self, index):
        if index < 0 or index > (self.length()-1):
            print("The input index is out of range!")
        elif index == 0:
            self._head = self._head._next
        else:
            count = 1
            pre, cur = self._head, self._head._next
            while count<index:
                count += 1
                pre, cur = cur, cur._next
            pre._next = cur._next

    # search index of node according to the value, if not this value, return False
    def searchbyvalue(self, value):
        count = 0
        cur = self._head
        index = []
        while cur != None:
            if cur._value == value:
                index.append(count)
            count += 1
            cur = cur._next
        if not index:
            return False
        else:
            return index

    # search the value of node according to the index
    def searchbyindex(self, index):
        count = 0
        cur = self._head
        if index < 0 or index > (self.length()-1):
            print("The input index is out of range")
        else:
            while count < index:
                count += 1
                cur = cur._next
            return cur._value
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

用Python实现链表 的相关文章

随机推荐

  • element table显示滚动条

    1 tableX为要显示滚动条的类名 2 显示横向滚动条 3 tableX el table scrollable x el table body wrapper 4 padding 0 0 5px 0 5 margin 0 0 5px 0
  • 【最新】手把手教你在VMware中安装Ubuntu虚拟机

    手把手教你在Vmware中安装Ubuntu虚拟机 一 下载VMware和Ubuntu系统官方镜像 1 下载VMware 2 下载Ubuntu系统官方镜像 二 安装VMware和Ubuntu虚拟机 1 安装VMware 2 安装Ubuntu镜
  • 电源学习总结(二)——线性稳压主要特点及原理

    文章目录 主要特点 内部结构 常见的三端线性稳压 AMS1117 主要特点 线性稳压最为突出的优点主要有成本低 噪声低 体积小 由于线性稳压结构简单 生产相对容易 因此其生产成本可以很低 同时其需要的外围器件也很少 一般只需要在输入端和输出
  • 【Python】教你写一个一键上传git的脚本(打包成exe)

    本篇博客来教你用Python写一个简单的git自动上传脚本 前言 为什么需要一个这样的东西 有的时候 我的学习代码其实没啥好commit的 写一个自动上传的脚本 就可以自动执行完所有的命令 而不需要自己手动进行git三板斧操作 项目代码已开
  • unplugin-vue-components 源码原理分析

    unplugin vue components 是一款按需自动导入Vue组件的库 支持 Vue2 和 Vue3 同时支持组件和指令 使用此插件库后 不再需要手动导入组件 插件会自动识别按需导入组件以及对应样式 我们只需要像全局组件那样使用即
  • 【笔记】SemGCN

    一 论文总结 1 1 核心贡献 提出了一种改进的图卷积操作 称为语义图卷积 SemGConv 它源自cnn 其关键思想是学习图中暗示的边的信道权值 然后将它们与核矩阵结合起来 这大大提高了图卷积的能力 其次 我们引入了SemGCN 其中Se
  • Unity PlayerPrefs(数据持久化)

    PlayerPrefs Unity3D中的数据持久化是以键值的形式存储的 可以看作是一个字典 Unity3D中值是通过键名来读取的 当值不存在时 返回默认值 目前Unity3D中只支持int string float三种数据类型的读取 参考
  • android开发工具!Android性能优化常见问题,灵魂拷问

    前言 今年上半年其实就已经有了换工作的想法 奈何疫情原因和岗位缩减 加之信心不足 到六月底投递了百度的Android岗位 本以为像我这种非211 985没工作经验的渣渣只能被直接pass 结果却意外的收到了电话 真是受宠若惊 经过电面 技术
  • 51单片机入学第八课——8*8点阵屏

    文章目录 LED点阵屏 点阵屏电路图 74HC595芯片 串入并出 使用方法 编程 点亮一个点 显示汉字 PCtoLCD 2002 编写代码 总结 LED点阵屏 LED点阵屏和数码管工作都是是靠二极管发光 但工作原理与矩阵键盘有些类似 在后
  • springboot2.0整合logback日志(详细)

    一 近期自己的项目想要一个记录日志的功能 而springboot本身就内置了日志功能 然而想要输入想要的日志 并且输出到磁盘 然后按天归档 或者日志的切分什么的 自带的日志仅仅具有简单的功能 百度了一番 总结如下 适合大多数的应用场景 二
  • python线程池ThreadPoolExecutor使用

    假设我们必须多线程任务创建大量线程 由于线程太多 因此可能会有很多性能问题 这在计算上会是最昂贵的 一个主要问题可能是吞吐量受限 我们可以通过创建一个线程池来解决这个问题 一个线程池可以被定义为一组预先实例化和空闲的线程 它们随时可以开始工
  • 微信小程序请求库的封装方法

    1 文档地址 微信官方文档 wx request网络请求 2 项目使用 根目录下新建utils gt request js 作为请求通用库 接口地址 const DEV URL http localhost 22667 const PROD
  • 常用python程序

    压缩文件 import zipfile import os def zipDir dirpath outFullName 压缩指定文件夹 param dirpath 目标文件夹路径 param outFullName 压缩文件保存路径 xx
  • linux环境用opencv读取图片,基于Linux下OpenCV的人脸识别模块设计

    金笑雪 张琳琳 高丹 张黎 摘 要 近年来 图像识别技术正在向更加直观 可靠的方向发展 其中人脸识别技术具有极高的研究价值 应用得也最为广泛 通过对Linux系统下OpenCV的研究 利用OpenCv Python3 4设计出一个图像识别系
  • OpenWRT添加模块(一)Makefile和Config.in

    第一次接触到openwrt 真是被毁三观啊 不要说makefile 连源代码在哪里都找不到 知道嵌入式系统水深 没想到迈出第一步就没过了脖子 好在旁边有人指点 直接在芯片厂商提供的既有代码上做二次开发 项目进展倒也完全满足了前期计划的目标
  • Linux基础笔记

    第一章 一 网络配置 网络三要素 ip地址 子网掩码 255 255 255 0 网关 ifconfig 查看网络 hostname 查看本机名称 hostname 更改主机名 etc hosts 网络映射配置文件 etc sysconfi
  • 【使用TensorRT自带的plugin】

    0 背景 在之前的文章TensorRT的plugin实现中介绍了 如何从零实现一个TensorRT的plugin 这篇文章来介绍如何使用TensorRT自带的plugin 将其添加到Network Definition中加速我们的模型 自T
  • js延时案例

    例子 setTimeout function gift css display block 3000 js延迟函数delay的使用 const delay ms gt new Promise resolve reject gt setTim
  • Unity 场景烘焙原理

    一 基础四种烘焙方式 1 静态灯光下静态物体烘焙 2 静态灯光下动态物体烘焙 3 动态灯光下静态物体烘焙 4 动态灯光下动态物体烘焙 二 实现方法 1 静态灯光下静态物体烘焙设置如下 灯光类型设置为Baked模式 模型预设右上角设置为Sta
  • 用Python实现链表

    摘要 在C C 语言中 常用结构体 指针来实现链表 而在Python语言中 使用类 class 来实现链表 一 创建节点 Node 链表由多个节点 Node 组成 而每个节点都有两要素组成 1 value 该节点的值 2 next 指向下一