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中的mock库对Python代码进行模拟测试
Apr 16 Python
numpy数组拼接简单示例
Dec 15 Python
Python读写zip压缩文件的方法
Aug 29 Python
python爬虫 基于requests模块的get请求实现详解
Aug 20 Python
Python3分析处理声音数据的例子
Aug 27 Python
Django文件上传与下载(FileFlid)
Oct 06 Python
无需压缩软件,用python帮你操作压缩包
Aug 17 Python
Python特殊属性property原理及使用方法解析
Oct 09 Python
Python random模块的使用示例
Oct 10 Python
Python QT组件库qtwidgets的使用
Nov 02 Python
详解pandas apply 并行处理的几种方法
Feb 24 Python
Flask response响应的具体使用
Jul 15 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方法调用模式与函数调用模式简例
2011/09/20 PHP
网上抓的一个特效
2007/05/11 Javascript
js中事件的处理与浏览器对象示例介绍
2013/11/29 Javascript
jquery学习总结(超级详细)
2014/09/04 Javascript
浅谈 javascript 事件处理
2015/01/04 Javascript
jQuery实现鼠标经过购物车出现下拉框代码(推荐)
2016/07/21 Javascript
原生js代码实现图片放大境效果
2016/10/30 Javascript
jQuey将序列化对象在前台显示地实现代码(方法总结)
2016/12/13 Javascript
基于node.js依赖express解析post请求四种数据格式
2017/02/13 Javascript
微信小程序开发之相册选择和拍照详解及实例代码
2017/02/22 Javascript
AngularJS动态添加数据并删除的实例
2018/02/27 Javascript
vue配置多页面的实现方法
2018/05/22 Javascript
vuex 动态注册方法 registerModule的实现
2019/07/03 Javascript
layui-table获得当前行的上/下一行数据的例子
2019/09/24 Javascript
js实现点击生成随机div
2020/01/16 Javascript
Pyramid Mako模板引入helper对象的步骤方法
2013/11/27 Python
在DigitalOcean的服务器上部署flaskblog应用
2015/12/19 Python
python 获取一个值在某个区间的指定倍数的值方法
2018/11/12 Python
python flask框架实现重定向功能示例
2019/07/02 Python
决策树剪枝算法的python实现方法详解
2019/09/18 Python
Python 私有属性和私有方法应用场景分析
2020/06/19 Python
详解Python3 定义一个跨越多行的字符串的多种方法
2020/09/06 Python
Python unittest生成测试报告过程解析
2020/09/08 Python
总结Pyinstaller的坑及终极解决方法(小结)
2020/09/21 Python
突袭HTML5之Javascript API扩展2—地理信息服务及地理位置API学习
2013/01/31 HTML / CSS
html5简介_动力节点Java学院整理
2017/07/07 HTML / CSS
HTML5中图片之间的缝隙完美解决方法
2017/07/07 HTML / CSS
日本最大的药妆连锁店:Matsukiyo松本清药妆店
2017/11/23 全球购物
FLOS美国官网:意大利高级照明工艺的传奇
2018/08/07 全球购物
为娇小女性量身打造:Petite Studio
2018/11/01 全球购物
天鹅的故事教学反思
2014/02/04 职场文书
安全责任协议书
2014/04/21 职场文书
青年安全生产示范岗事迹材料
2014/05/04 职场文书
岗位安全生产责任书
2014/07/28 职场文书
创先争优个人总结
2015/03/04 职场文书
酒店销售经理岗位职责
2015/04/02 职场文书