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使用正则匹配实现抓图代码分享
Apr 02 Python
在Python中操作字符串之startswith()方法的使用
May 20 Python
基于Python中capitalize()与title()的区别详解
Dec 09 Python
用python生成1000个txt文件的方法
Oct 25 Python
python 找出list中最大或者最小几个数的索引方法
Oct 30 Python
Python循环实现n的全排列功能
Sep 16 Python
python3 pathlib库Path类方法总结
Dec 26 Python
python_mask_array的用法
Feb 18 Python
Python基于paramunittest模块实现excl参数化
Apr 26 Python
python构造IP报文实例
May 05 Python
使用Python将语音转换为文本的方法
Aug 10 Python
pycharm代码删除恢复的方法
Jun 26 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根据身份证号码计算年龄的实例代码
2014/01/18 PHP
Codeigniter中禁止A Database Error Occurred错误提示的方法
2014/06/12 PHP
CI框架的安全性分析
2016/05/18 PHP
PHP从零开始打造自己的MVC框架之入口文件实现方法详解
2019/06/03 PHP
php简单计算权重的方法示例【适合抽奖类应用】
2019/06/10 PHP
基于JQuery.timer插件实现一个计时器
2010/04/25 Javascript
用jquery仿做发微博功能示例
2014/04/18 Javascript
jQuery Uploadify 上传插件出现Http Error 302 错误的解决办法
2015/12/12 Javascript
简单介绍jsonp 使用小结
2016/01/27 Javascript
js去字符串前后空格的实现方法
2016/02/26 Javascript
js事件驱动机制 浏览器兼容处理方法
2016/07/23 Javascript
javascript中json基础知识详解
2017/01/19 Javascript
基于JavaScript实现的插入排序算法分析
2017/04/14 Javascript
基于$.ajax()方法从服务器获取json数据的几种方式总结
2018/01/31 Javascript
Vue.js实现的计算器功能完整示例
2018/07/11 Javascript
深入理解JavaScript 中的执行上下文和执行栈
2018/10/23 Javascript
vue实现PC端录音功能的实例代码
2019/06/05 Javascript
webpack + vue 打包生成公共配置文件(域名) 方便动态修改
2019/08/29 Javascript
微信小程序 下拉刷新及上拉加载原理解析
2019/11/06 Javascript
使用Vue-cli 中为单独页面设置背景图片铺满全屏
2020/07/17 Javascript
在Python的Django框架中包装视图函数
2015/07/20 Python
spark: RDD与DataFrame之间的相互转换方法
2018/06/07 Python
django celery redis使用具体实践
2019/04/08 Python
python实现QQ批量登录功能
2019/06/19 Python
python3字符串操作总结
2019/07/24 Python
使用TensorFlow-Slim进行图像分类的实现
2019/12/31 Python
详解python tkinter包获取本地绝对路径(以获取图片并展示)
2020/09/04 Python
中国领先的专业家电网购平台:国美在线
2016/12/25 全球购物
时尚设计师手表:The Watch Cabin
2018/10/06 全球购物
维氏瑞士军刀英国网站:Victorinox英国
2019/07/04 全球购物
护理专业优质毕业生自荐书
2014/01/31 职场文书
财务主管岗位职责
2014/02/28 职场文书
房产转让协议书(2014版)
2014/09/30 职场文书
小学教育见习总结
2015/06/23 职场文书
Pygame Time时间控制的具体使用详解
2021/11/17 Python
Mysql存储过程、触发器、事件调度器使用入门指南
2022/01/22 MySQL