python实现双链表


Posted in Python onMay 25, 2022

本文实例为大家分享了python实现双链表的具体代码,供大家参考,具体内容如下

实现双链表需要注意的地方

1、如何插入元素,考虑特殊情况:头节点位置,尾节点位置;一般情况:中间位置
2、如何删除元素,考虑特殊情况:头结点位置,尾节点位置;一般情况:中间位置

代码实现

1.构造节点的类和链表类

class Node:
    def __init__(self, data):
        self.data = data
        self.next = None
        self.previous = None


class DoubleLinkList:
    '''双链表'''

    def __init__(self, node=None):
        self._head = node

以下方法均在链表类中实现

2. 判断链表是否为空

def is_empty(self):
        return self._head is None

3. 输出链表的长度

def length(self):
        count = 0
        if self.is_empty():
            return count
        else:
            current = self._head
            while current is not None:
                count += 1
                current = current.next
        return count

4. 遍历链表

def travel(self):
        current = self._head
        while current is not None:
            print("{0}".format(current.data), end=" ")
            current = current.next
        print("")

5.头插法增加新元素

def add(self, item):
        node = Node(item)

        # 如果链表为空,让头指针指向当前节点
        if self.is_empty():
            self._head = node

        # 注意插入的顺序,
        else:
            node.next = self._head
            self._head.previous = node
            self._head = node

6. 尾插法增加新元素

def append(self, item):
        node = Node(item)

        # 如果链表为空,则直接让头指针指向该节点
        if self.is_empty():
            self._head = node

        # 需要找到尾节点,然后让尾节点的与新的节点进行连接
        else:
            current = self._head
            while current.next is not None:
                current = current.next
            current.next = node
            node.previous = current

7. 查找元素是否存在链表中

def search(self, item):
        current = self._head
        found = False
        while current is not None and not found:
            if current.data == item:
                found = True
            else:
                current = current.next
        return found

8. 在某个位置中插入元素

def insert(self, item, pos):

        # 特殊位置,在第一个位置的时候,头插法
        if pos <= 0:
            self.add(item)

        # 在尾部的时候,使用尾插法
        elif pos > self.length() - 1:
            self.append(item)

        # 中间位置
        else:
            node = Node(item)
            current = self._head
            count = 0
            while count < pos - 1:
                current = current.next
                count += 1

            # 找到了要插入位置的前驱之后,进行如下操作
            node.previous = current
            node.next = current.next
            current.next.previous = node
            current.next = node

python实现双链表

 # 换一个顺序也可以进行
def insert2(self, item, pos):
        if pos <= 0:
            self.add(item)
        elif pos > self.length() - 1:
            self.append(item)
        else:
            node = Node(item)
            current = self._head
            count = 0
            while count < pos:
                current = current.next
                count += 1

            node.next = current
            node.previous = current.previous
            current.previous.next = node
            current.previous = node

9. 删除元素

def remove(self, item):
        current = self._head
        if self.is_empty():
            return
        elif current.data == item:
            # 第一个节点就是目标节点,那么需要将下一个节点的前驱改为None 然后再将head指向下一个节点
            current.next.previous = None
            self._head = current.next
        else:

            # 找到要删除的元素节点
            while current is not None and current.data != item:
                current = current.next
            if current is None:
                print("not found {0}".format(item))

            # 如果尾节点是目标节点,让前驱节点指向None
            elif current.next is None:
                current.previous.next = None

            # 中间位置,因为是双链表,可以用前驱指针操作
            else:
                current.previous.next = current.next
                current.next.previous = current.previous
# 第二种写法
    def remove2(self, item):
        """删除元素"""
        if self.is_empty():
            return
        else:
            cur = self._head
            if cur.data == item:
                # 如果首节点的元素即是要删除的元素
                if cur.next is None:
                    # 如果链表只有这一个节点
                    self._head = None
                else:
                    # 将第二个节点的prev设置为None
                    cur.next.prev = None
                    # 将_head指向第二个节点
                    self._head = cur.next
                return
            while cur is not None:
                if cur.data == item:
                    # 将cur的前一个节点的next指向cur的后一个节点
                    cur.prev.next = cur.next
                    # 将cur的后一个节点的prev指向cur的前一个节点
                    cur.next.prev = cur.prev
                    break
                cur = cur.next

10. 演示

my_list = DoubleLinkList()


print("add操作")
my_list.add(98)
my_list.add(99)
my_list.add(100)
my_list.travel()
print("{:#^50}".format(""))

print("append操作")
my_list.append(86)
my_list.append(85)
my_list.append(88)
my_list.travel()
print("{:#^50}".format(""))

print("insert2操作")
my_list.insert2(66, 3)
my_list.insert2(77, 0)
my_list.insert2(55, 10)
my_list.travel()
print("{:#^50}".format(""))


print("insert操作")
my_list.insert(90, 4)
my_list.insert(123, 5)
my_list.travel()
print("{:#^50}".format(""))

print("search操作")
print(my_list.search(100))
print(my_list.search(1998))
print("{:#^50}".format(""))

print("remove操作")
my_list.remove(56)
my_list.remove(123)
my_list.remove(77)
my_list.remove(55)
my_list.travel()
print("{:#^50}".format(""))

print("remove2操作")
my_list.travel()
my_list.remove2(100)
my_list.remove2(99)
my_list.remove2(98)
my_list.travel()

python实现双链表

以上就是本文的全部内容,希望对大家的学习有所帮助。


Tags in this post...

Python 相关文章推荐
Python MySQLdb模块连接操作mysql数据库实例
Apr 08 Python
python文件操作之目录遍历实例分析
May 20 Python
使用python opencv对目录下图片进行去重的方法
Jan 12 Python
python dlib人脸识别代码实例
Apr 04 Python
Python提取转移文件夹内所有.jpg文件并查看每一帧的方法
Jun 27 Python
Python + OpenCV 实现LBP特征提取的示例代码
Jul 11 Python
python3模拟实现xshell远程执行liunx命令的方法
Jul 12 Python
解决Python3用PIL的ImageFont输出中文乱码的问题
Aug 22 Python
在python中利用dict转json按输入顺序输出内容方式
Feb 27 Python
MATLAB数学建模之画图汇总
Jul 16 Python
Python调用JavaScript代码的方法
Oct 27 Python
详解python字符串驻留技术
May 21 Python
Python实现双向链表
May 25 #Python
python区块链持久化和命令行接口实现简版
May 25 #Python
python区块链实现简版工作量证明
May 25 #Python
pycharm无法安装cv2模块问题
May 20 #Python
python中 Flask Web 表单的使用方法
May 20 #Python
Python OpenGL基本配置方式
May 20 #Python
Python面试不修改数组找出重复的数字
May 20 #Python
You might like
PHP中substr函数字符串截取用法分析
2016/01/07 PHP
laravel 字段格式化 modle 字段类型转换方法
2019/09/30 PHP
javascript延时重复执行函数 lLoopRun.js
2007/06/29 Javascript
JavaScript 5 新增 Array 方法实现介绍
2012/02/06 Javascript
javascript工具库代码
2012/03/29 Javascript
jQuery 选择器详解
2015/01/19 Javascript
jQuery插件Elastislide实现响应式的焦点图无缝滚动切换特效
2015/04/12 Javascript
easyui validatebox验证
2016/04/29 Javascript
基于 webpack2 实现的多入口项目脚手架详解
2017/06/26 Javascript
Javascript中Promise的四种常用方法总结
2017/07/14 Javascript
详解Vue2.x-directive的学习笔记
2017/07/17 Javascript
JS轮播图实现简单代码
2021/02/19 Javascript
在vue里面设置全局变量或数据的方法
2018/03/09 Javascript
小程序获取周围IBeacon设备的方法
2018/10/31 Javascript
微信小程序如何实现全局重新加载
2019/06/05 Javascript
layui加载表格,绑定新增,编辑删除,查看按钮事件的例子
2019/09/06 Javascript
[36:43]NB vs Optic 2018国际邀请赛小组赛BO1 B组加赛 8.19
2018/08/21 DOTA
python如何重载模块实例解析
2018/01/25 Python
python之消除前缀重命名的方法
2018/10/21 Python
Django2.1集成xadmin管理后台所遇到的错误集锦(填坑)
2018/12/20 Python
Python调用钉钉自定义机器人的实现
2020/01/03 Python
Python脚本去除文件的只读性操作
2020/03/05 Python
python3 配置logging日志类的操作
2020/04/08 Python
Python私有属性私有方法应用实例解析
2020/09/15 Python
利用Python优雅的登录校园网
2020/10/21 Python
详解Html5中video标签那些属性和方法
2019/07/01 HTML / CSS
Rockport乐步美国官网:风靡美国的白宫鞋
2016/11/24 全球购物
迪士尼英国官方商店:shopDisney UK
2019/09/21 全球购物
某公司.Net方向面试题
2014/04/24 面试题
营销人才自我鉴定范文
2013/12/25 职场文书
语文教学随笔感言
2014/02/18 职场文书
5s推行计划书
2014/05/06 职场文书
模具专业求职信
2014/06/26 职场文书
好媳妇事迹材料
2014/12/24 职场文书
Python 把两层列表展开平铺成一层(5种实现方式)
2021/04/07 Python
详细谈谈MYSQL中的COLLATE是什么
2021/06/11 MySQL