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执行shell获取硬件参数写入mysql的方法
Dec 29 Python
python处理二进制数据的方法
Jun 03 Python
Python实现的文本对比报告生成工具示例
May 22 Python
numpy中矩阵合并的实例
Jun 15 Python
python实现zabbix发送短信脚本
Sep 17 Python
Python利用heapq实现一个优先级队列的方法
Feb 03 Python
Pytorch中index_select() 函数的实现理解
Nov 19 Python
pytorch中tensor.expand()和tensor.expand_as()函数详解
Dec 27 Python
Python PIL库图片灰化处理
Apr 07 Python
python查看矩阵的行列号以及维数方式
May 22 Python
浅谈keras中Dropout在预测过程中是否仍要起作用
Jul 09 Python
教你使用Python获取QQ音乐某个歌手的歌单
Apr 03 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
DOTA2 1月28日更新:监管系统降临刀塔世界
2021/01/28 DOTA
PHP迭代器实现斐波纳契数列的函数
2013/11/12 PHP
大家在抢红包,程序员在研究红包算法
2015/08/31 PHP
php阿拉伯数字转中文人民币大写
2015/12/21 PHP
PHP简单实现DES加密解密的方法
2016/07/12 PHP
用HTML/JS/PHP方式实现页面延时跳转的简单实例
2016/07/18 PHP
PHP去除字符串最后一个字符的三种方法实例
2017/03/01 PHP
PHP简单实现记录网站访问量功能示例
2018/06/06 PHP
js判断横竖屏及禁止浏览器滑动条示例
2014/04/29 Javascript
jQuery 中国省市两级联动选择附图
2014/05/14 Javascript
跟我学习javascript的prototype使用注意事项
2015/11/17 Javascript
js全选按钮的实现方法
2015/11/17 Javascript
基于BootStrap Metronic开发框架经验小结【七】数据的导入、导出及附件的查看处理
2016/05/12 Javascript
jQuery+ajax实现滚动到页面底部自动加载图文列表效果(类似图片懒加载)
2016/06/07 Javascript
jQuery Easyui快速入门教程
2016/08/21 Javascript
jQuery弹出div层过2秒自动消失
2016/11/29 Javascript
vue2.0实现导航菜单切换效果
2017/05/08 Javascript
JS倒计时实例_天时分秒
2017/08/22 Javascript
基于bootstrap写的一点localStorage本地储存
2017/11/21 Javascript
Vue 请求传公共参数的操作
2020/07/31 Javascript
vue实现简单计算商品价格
2020/09/14 Javascript
Python获取文件所在目录和文件名的方法
2017/01/12 Python
Python3导入CSV文件的实例(跟Python2有些许的不同)
2018/06/22 Python
python实现图片批量压缩程序
2018/07/23 Python
pandas 条件搜索返回列表的方法
2018/10/30 Python
Python中安装easy_install的方法
2018/11/18 Python
Python多线程处理实例详解【单进程/多进程】
2019/01/30 Python
python脚本执行CMD命令并返回结果的例子
2019/08/14 Python
CSS3教程:新增加的结构伪类
2009/04/02 HTML / CSS
菲律宾票务网站:StubHub菲律宾
2018/04/21 全球购物
面向对象编程OOP的优点
2013/01/22 面试题
计划生育诚信协议书
2014/11/02 职场文书
心灵捕手观后感
2015/06/02 职场文书
MySQL 逻辑备份与恢复测试的相关总结
2021/05/14 MySQL
2022漫威和DC电影上映作品
2022/04/05 欧美动漫
Nginx跨域问题解析与解决
2022/08/05 Servers