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 getopt 参数处理小示例
Jun 09 Python
利用Python画ROC曲线和AUC值计算
Sep 19 Python
使用python编写监听端
Apr 12 Python
python对excel文档去重及求和的实例
Apr 18 Python
TensorFlow入门使用 tf.train.Saver()保存模型
Apr 24 Python
Python数据可视化教程之Matplotlib实现各种图表实例
Jan 13 Python
在Python 不同级目录之间模块的调用方法
Jan 19 Python
pandas 数据索引与选取的实现方法
Jun 21 Python
树莓派用python中的OpenCV输出USB摄像头画面
Jun 22 Python
python正则-re的用法详解
Jul 28 Python
Pyecharts 动态地图 geo()和map()的安装与用法详解
Mar 25 Python
Python特殊属性property原理及使用方法解析
Oct 09 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
杏林同学录(七)
2006/10/09 PHP
抓取并下载CSS中所有图片文件的php代码
2011/09/26 PHP
PHP+Ajax实时自动检测是否联网的方法
2015/07/01 PHP
thinkphp3.2实现在线留言提交验证码功能
2017/07/19 PHP
javascript onkeydown,onkeyup,onkeypress,onclick,ondblclick
2009/02/04 Javascript
JavaScript 对象模型 执行模型
2009/12/06 Javascript
如何让页面在打开时自动刷新一次让图片全部显示
2012/12/17 Javascript
jquery 漂亮的删除确认和提交无刷新删除示例
2013/11/13 Javascript
node.js中Socket.IO的进阶使用技巧
2014/11/04 Javascript
javascript实现当前页导航激活的方法
2015/02/27 Javascript
javascript常用方法总结
2015/05/14 Javascript
详解jQuery向动态生成的内容添加事件响应jQuery live()方法
2015/11/02 Javascript
jquery中$.fn和图片滚动效果实现的必备知识总结
2017/04/21 jQuery
JS触摸事件、手势事件详解
2017/05/04 Javascript
微信小程序实现手势图案锁屏功能
2018/01/30 Javascript
vue 子组件向父组件传值方法
2018/02/26 Javascript
详解vue数组遍历方法forEach和map的原理解析和实际应用
2018/11/15 Javascript
微信小程序时间标签和时间范围的联动效果
2019/02/15 Javascript
angular 服务随记小结
2019/05/06 Javascript
微信小程序如何获取用户头像和昵称
2019/09/23 Javascript
微信小程序利用for循环解决内容变更问题
2020/03/05 Javascript
Bootstrap告警框(alert)实现弹出效果和短暂显示后上浮消失的示例代码
2020/08/27 Javascript
Vue 组件注册全解析
2020/12/17 Vue.js
Python利用pyHook实现监听用户鼠标与键盘事件
2014/08/21 Python
树莓派4B+opencv4+python 打开摄像头的实现方法
2019/10/18 Python
浅谈python的elementtree模块处理中文注意事项
2020/03/06 Python
学校教研活动总结
2014/07/02 职场文书
医学检验专业自荐信
2014/09/18 职场文书
施工安全协议书范本
2014/09/26 职场文书
租车协议书
2015/01/27 职场文书
社会实践活动总结格式
2015/05/11 职场文书
企业员工辞职信范文
2015/05/12 职场文书
小学生手册家长意见
2015/06/03 职场文书
企业宣传语大全
2015/07/13 职场文书
教你怎么用Python操作MySql数据库
2021/05/31 Python
Python卷积神经网络图片分类框架详解分析
2021/11/07 Python