python实现双链表

 更新时间:2022年05月25日 08:16:38   作者:我的加奈  
这篇文章主要为大家详细介绍了python实现双链表,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了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

 # 换一个顺序也可以进行
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编写简单爬虫资料汇总

    python编写简单爬虫资料汇总

    本文给大家汇总介绍了下几种使用Python编写简单爬虫的方法和代码,非常的不错,这里分享给大家,希望大家能够喜欢。
    2016-03-03
  • Python3.9又更新了:dict内置新功能

    Python3.9又更新了:dict内置新功能

    这篇文章主要介绍了Python3.9又更新了:dict内置新功能,从文档中,我们可以看到官方透露的对 dict、math 等组件增加的新特性,以及下一步的开发进展
    2020-02-02
  • python自动发微信监控报警

    python自动发微信监控报警

    这篇文章主要为大家详细介绍了python自动发微信监控报警,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-09-09
  • python通过apply使用元祖和列表调用函数实例

    python通过apply使用元祖和列表调用函数实例

    这篇文章主要介绍了python通过apply使用元祖和列表调用函数,实例分析了python中apply方法的使用技巧,需要的朋友可以参考下
    2015-05-05
  • Python+wxPython实现文件名批量处理

    Python+wxPython实现文件名批量处理

    在日常的文件管理中,我们经常需要对文件进行批量处理以符合特定的命名规则或需求,本文主要介绍了如何使用wxPython进行文件夹中文件名的批量处理,需要的可以参考下
    2024-04-04
  • python机器学习实战之最近邻kNN分类器

    python机器学习实战之最近邻kNN分类器

    这篇文章主要介绍了python机器学习实战之最近邻kNN分类器,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-12-12
  • Python人脸检测实战之疲劳检测

    Python人脸检测实战之疲劳检测

    本文主要介绍了实现疲劳检测:如果眼睛已经闭上了一段时间,我们会认为他们开始打瞌睡并发出警报来唤醒他们并引起他们的注意。感兴趣的朋友可以了解一下
    2021-12-12
  • Python3解决棋盘覆盖问题的方法示例

    Python3解决棋盘覆盖问题的方法示例

    这篇文章主要介绍了Python3解决棋盘覆盖问题的方法,简单描述了棋盘覆盖问题的概念、原理及Python相关操作技巧,需要的朋友可以参考下
    2017-12-12
  • Python基于wxPython和FFmpeg开发一个视频标签工具

    Python基于wxPython和FFmpeg开发一个视频标签工具

    在当今数字媒体时代,视频内容的管理和标记变得越来越重要,无论是研究人员需要对实验视频进行时间点标记,还是个人用户希望对家庭视频进行分类整理,一个高效的视频标签工具都是不可或缺的,本文将详细分析一个基于Python、wxPython和FFmpeg开发的视频标签工具
    2025-04-04
  • pycharm 设置项目的根目录教程

    pycharm 设置项目的根目录教程

    今天小编就为大家分享一篇pycharm 设置项目的根目录教程,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-02-02

最新评论