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 uuid模块使用实例
Apr 08 Python
Python基于pygame实现的弹力球效果(附源码)
Nov 11 Python
Python操作mysql数据库实现增删查改功能的方法
Jan 15 Python
python 列表降维的实例讲解
Jun 28 Python
Python补齐字符串长度的实例
Nov 15 Python
使用Pandas对数据进行筛选和排序的实现
Jul 29 Python
python django model联合主键的例子
Aug 06 Python
Django中使用haystack+whoosh实现搜索功能
Oct 08 Python
构建高效的python requests长连接池详解
May 02 Python
python异常处理之try finally不报错的原因
May 18 Python
Python子进程subpocess原理及用法解析
Jul 16 Python
Python 数据科学 Matplotlib图库详解
Jul 07 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作为网站开发语言的原因分享
2012/01/03 PHP
PHP多例模式介绍
2013/06/24 PHP
php中青蛙跳台阶的问题解决方法
2018/10/14 PHP
php和vue配合使用技巧和方法
2019/05/09 PHP
PHP 7.4中使用预加载的方法详解
2019/07/08 PHP
Google排名中的10个最著名的 JavaScript库
2010/04/27 Javascript
jquery 实现两级导航菜单附效果图
2014/03/07 Javascript
JQuery判断radio(单选框)是否选中和获取选中值方法总结
2015/04/15 Javascript
JavaScript中的getDay()方法使用详解
2015/06/09 Javascript
如何使用PHP+jQuery+MySQL实现异步加载ECharts地图数据(附源码下载)
2016/02/23 Javascript
JavaScript获取客户端IP的方法(新方法)
2016/03/11 Javascript
jQuery实现漂亮实用的商品图片tips提示框效果(无图片箭头+阴影)
2016/04/16 Javascript
jQuery简单实现中间浮窗效果
2016/09/04 Javascript
BootStrap 可编辑表Table格
2016/11/24 Javascript
jQuery中table数据的值拷贝和拆分
2017/03/19 Javascript
node.js中cluster的使用教程
2017/06/09 Javascript
基于JSON数据格式详解
2017/08/31 Javascript
在 webpack 中使用 ECharts的实例详解
2018/02/05 Javascript
vue绑定事件后获取绑定事件中的this方法
2018/09/15 Javascript
详解基于Vue的支持数据双向绑定的select组件
2019/09/02 Javascript
python 快速排序代码
2009/11/23 Python
Python中for循环详解
2014/01/17 Python
python修改注册表终止360进程实例
2014/10/13 Python
python下载图片实现方法(超简单)
2017/07/21 Python
scrapy-redis的安装部署步骤讲解
2019/02/27 Python
Python实现Selenium自动化Page模式
2019/07/14 Python
浅谈python量化 双均线策略(金叉死叉)
2020/06/03 Python
Tensorflow中k.gradients()和tf.stop_gradient()用法说明
2020/06/10 Python
利用简洁的图片预加载组件提升html5移动页面的用户体验
2016/03/11 HTML / CSS
HTML5学习笔记之History API
2015/02/26 HTML / CSS
德国帽子专家:Hutshopping
2019/11/03 全球购物
作文批改评语大全
2014/04/23 职场文书
辞职信标准格式
2015/02/27 职场文书
行政人事主管岗位职责
2015/04/11 职场文书
python绘制箱型图
2021/04/27 Python
Python类方法总结讲解
2021/07/26 Python