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删除java文件头上版权信息的方法
Jul 31 Python
python的类变量和成员变量用法实例教程
Aug 25 Python
python爬虫之百度API调用方法
Jun 11 Python
Python2包含中文报错的解决方法
Jul 09 Python
python得到电脑的开机时间方法
Oct 15 Python
Python图像的增强处理操作示例【基于ImageEnhance类】
Jan 03 Python
python设定并获取socket超时时间的方法
Jan 12 Python
基于python历史天气采集的分析
Feb 14 Python
python能做什么 python的含义
Oct 12 Python
python反转列表的三种方式解析
Nov 08 Python
Python requests上传文件实现步骤
Sep 15 Python
Python数据可视化之绘制柱状图和条形图
May 25 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新手上路(十)
2006/10/09 PHP
php学习笔记 php中面向对象三大特性之一[封装性]的应用
2011/06/13 PHP
从手册去理解分析PHP session机制
2011/07/17 PHP
基于AppServ,XAMPP,WAMP配置php.ini去掉警告信息(NOTICE)的方法详解
2013/05/07 PHP
PHP使用DES进行加密与解密的方法详解
2013/06/06 PHP
php生成随机数的三种方法
2014/09/10 PHP
简单谈谈PHP中的Reload操作
2016/12/12 PHP
PHP以json或xml格式返回请求数据的方法
2018/05/31 PHP
在b/s开发中经常用到的javaScript技术
2006/08/23 Javascript
js实现DIV的一些简单控制
2007/06/04 Javascript
js 定时器setTimeout无法调用局部变量的解决办法
2013/11/28 Javascript
使用Nodejs开发微信公众号后台服务实例
2014/09/03 NodeJs
BootStrap入门教程(二)之固定的内置样式
2016/09/19 Javascript
Vue2.x中的Render函数详解
2017/05/30 Javascript
Underscore之Array_动力节点Java学院整理
2017/07/10 Javascript
javascript 中事件冒泡和事件捕获机制的详解
2017/09/01 Javascript
vue.js使用v-model实现表单元素(input) 双向数据绑定功能示例
2019/03/08 Javascript
解决Element中el-date-picker组件不回填的情况
2020/11/07 Javascript
javascript this指向相关问题及改变方法
2020/11/19 Javascript
聊聊vue 中的v-on参数问题
2021/01/29 Vue.js
[01:45]亚洲邀请赛互动指南虚拟物品介绍
2015/01/30 DOTA
深入Python解释器理解Python中的字节码
2015/04/01 Python
python字符串对其居中显示的方法
2015/07/11 Python
Python基于多线程实现抓取数据存入数据库的方法
2018/06/22 Python
详解pytorch tensor和ndarray转换相关总结
2020/09/03 Python
澳大利亚床上用品、浴巾和家居用品购物网站:Bambury
2020/04/16 全球购物
大学生毕业求职的自我评价
2013/09/29 职场文书
《罗布泊,消逝的仙湖》教学反思
2014/03/01 职场文书
合作协议书
2014/04/23 职场文书
三万活动总结
2014/04/28 职场文书
同事打架检讨书
2015/05/06 职场文书
信仰观后感
2015/06/03 职场文书
2016中考冲刺决心书
2015/09/22 职场文书
python自动统计zabbix系统监控覆盖率的示例代码
2021/04/03 Python
使用python绘制横竖条形图
2022/04/21 Python
python神经网络学习 使用Keras进行简单分类
2022/05/04 Python