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 相关文章推荐
详解python3中socket套接字的编码问题解决
Jul 01 Python
python 换位密码算法的实例详解
Jul 19 Python
pandas数据分组和聚合操作方法
Apr 11 Python
python+selenium实现自动抢票功能实例代码
Nov 23 Python
python实现海螺图片的方法示例
May 12 Python
tensorflow之自定义神经网络层实例
Feb 07 Python
python输出pdf文档的实例
Feb 13 Python
Python并发请求下限制QPS(每秒查询率)的实现代码
Jun 05 Python
基于Python+QT的gui程序开发实现
Jul 03 Python
python基于socket模拟实现ssh远程执行命令
Dec 05 Python
为2021年的第一场雪锦上添花:用matplotlib绘制雪花和雪景
Jan 05 Python
Django项目如何获得SSL证书与配置HTTPS
Apr 30 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
一个可以删除字符串中HTML标记的PHP函数
2006/10/09 PHP
php连接mysql数据库最简单的实现方法
2019/09/24 PHP
jquery 弹出登录窗口实现代码
2009/12/24 Javascript
javascript避免数字计算精度误差的方法详解
2014/03/05 Javascript
jQuery toggleClass应用实例(附效果图)
2014/04/06 Javascript
jQuery实现美观的多级动画效果菜单代码
2015/09/06 Javascript
jQuery实现选中弹出窗口选择框内容后赋值给文本框的方法
2015/11/23 Javascript
jQuery语法小结(超实用)
2015/12/31 Javascript
jQuery 3.0十大新特性最终版发布
2016/07/14 Javascript
Highcharts学习之坐标轴
2016/08/02 Javascript
jquery仿微信聊天界面
2017/05/06 jQuery
vue2.0路由切换后页面滚动位置不变BUG的解决方法
2018/03/14 Javascript
vue router总结 $router和$route及router与 router与route区别
2019/07/05 Javascript
Angular如何由模板生成DOM树的方法
2019/12/23 Javascript
使用Taro实现小程序商城的购物车功能模块的实例代码
2020/06/05 Javascript
[01:48]完美圣典齐天大圣至宝宣传片
2016/12/17 DOTA
python实现将文件夹内的每张图片批量分割成多张
2019/07/22 Python
Python队列RabbitMQ 使用方法实例记录
2019/08/05 Python
python图像处理模块Pillow的学习详解
2019/10/09 Python
Pytorch 使用 nii数据做输入数据的操作
2020/05/26 Python
Python 中的函数装饰器和闭包详解
2021/02/06 Python
js实现移动端H5页面手指滑动刻度尺功能
2017/11/16 HTML / CSS
突袭HTML5之Javascript API扩展2—地理信息服务及地理位置API学习
2013/01/31 HTML / CSS
WiFi云数码相框:Nixplay
2018/07/05 全球购物
试述DBMS的主要功能
2016/11/13 面试题
法学专业应届生求职信
2013/10/16 职场文书
红旗团支部事迹材料
2014/01/27 职场文书
教育英语专业毕业生的求职信
2014/03/13 职场文书
捐书倡议书
2014/08/29 职场文书
教育见习报告范文
2014/11/03 职场文书
党员思想汇报材料
2014/12/19 职场文书
商场圣诞节活动总结
2015/05/06 职场文书
2015年国培研修感言
2015/08/01 职场文书
golang 比较浮点数的大小方式
2021/05/02 Golang
Python还能这么玩之用Python做个小游戏的外挂
2021/06/04 Python
Python中递归以及递归遍历目录详解
2021/10/24 Python