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根据文件大小打log日志
Oct 09 Python
pygame学习笔记(6):完成一个简单的游戏
Apr 15 Python
Python的Flask框架应用调用Redis队列数据的方法
Jun 06 Python
总结用Pdb库调试Python的方式及常用的命令
Aug 18 Python
Python之Web框架Django项目搭建全过程
May 02 Python
Python2随机数列生成器简单实例
Sep 04 Python
Pyqt5 基本界面组件之inputDialog的使用
Jun 25 Python
Python如何通过Flask-Mail发送电子邮件
Jan 29 Python
pandas中的数据去重处理的实现方法
Feb 10 Python
简单介绍一下pyinstaller打包以及安全性的实现
Jun 02 Python
基于Python中Remove函数的用法讨论
Dec 11 Python
Python利用zhdate模块实现农历日期处理
Mar 31 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+memcache实现的网站在线人数统计代码
2014/07/04 PHP
Laravel中注册Facades的步骤详解
2016/03/16 PHP
phpfpm的作用和用法
2019/10/10 PHP
JS限制上传图片大小不使用控件在本地实现
2012/12/19 Javascript
JQuery中对Select的option项的添加、删除、取值
2013/08/25 Javascript
js中数组排序sort方法的原理分析
2014/11/20 Javascript
js中日期的加减法
2015/05/06 Javascript
基于jQuery滑动杆实现购买日期选择效果
2015/09/15 Javascript
原生javascript实现匀速运动动画效果
2016/02/26 Javascript
Javascript的动态增加类的实现方法
2016/10/20 Javascript
JS实现密码框的显示密码和隐藏密码功能示例
2016/12/26 Javascript
JS分页的实现(同步与异步)
2017/09/16 Javascript
angularJS1 url中携带参数的获取方法
2018/10/09 Javascript
vue+vuex+axios从后台获取数据存入vuex,组件之间共享数据操作
2020/07/31 Javascript
谈谈node.js中的模块系统
2020/09/01 Javascript
Python中的多重装饰器
2015/04/11 Python
python函数形参用法实例分析
2015/08/04 Python
用python写一个定时提醒程序的实现代码
2019/07/22 Python
python连接打印机实现打印文档、图片、pdf文件等功能
2020/02/07 Python
Python loguru日志库之高效输出控制台日志和日志记录
2020/03/07 Python
Jupyter notebook设置背景主题,字体大小及自动补全代码的操作
2020/04/13 Python
浅谈python 类方法/静态方法
2020/09/18 Python
使用HTML5做个画图板的方法介绍
2013/05/03 HTML / CSS
HTML5 Canvas阴影使用方法实例演示
2013/08/02 HTML / CSS
老人祝寿主持词
2014/03/28 职场文书
预备党员学习十八届三中全会精神思想汇报
2014/09/13 职场文书
关于工作经历的证明书
2014/10/11 职场文书
学生上课迟到检讨书
2015/01/01 职场文书
2015年度优秀员工自荐书
2015/03/06 职场文书
小学教师求职信范文
2015/03/20 职场文书
项目验收申请报告
2015/05/15 职场文书
通讯稿格式及范文
2015/07/22 职场文书
小学数学继续教育研修日志
2015/11/13 职场文书
音乐研修感悟
2015/11/18 职场文书
用Python编写简单的gRPC服务的详细过程
2021/07/04 Python
Java实现聊天机器人完善版
2021/07/04 Java/Android