python实现单向循环链表数据结构及其方法

简介: 首先要说明一下研究数据结构有什么用,可能就像高数之类的在生活中并没有多少用处,但是离不开他,很多大公司面试也会问这个东西;但是要落实到某一个具体的业务场景,我也不知道,但并不代表这些东西没用,也可能是这些模型只是为了让我们能理解更多有用的东西。

首先要说明一下研究数据结构有什么用,可能就像高数之类的在生活中并没有多少用处,但是离不开他,很多大公司面试也会问这个东西;但是要落实到某一个具体的业务场景,我也不知道,但并不代表这些东西没用,也可能是这些模型只是为了让我们能理解更多有用的东西。

今天说的是单向循环链表,昨天说了单向链表《python实现单向链表数据结构及其基本方法》,在此基础上我们说单向循环链表,其基本模型示图如下:

只不过在单向链表的基础上,最后一个节点纸箱头部,定义基本节点对象和链条对象。

class Node:
    def __init__(self, item):
        self.item = item  # 该节点值
        self.next = None   #  连接一下一个节点


class SinCycLinkedlist:

    def __init__(self):
        self._head = Node


然后实现循环链表对象的基本属性方法:是否为空、长度

class SinCycLinkedlist:

    def __init__(self):
        self._head = None

    def is_empty(self):
        """
        是否为空链表
        :return:
        """

        return None == self._head

    @property
    def length(self):
        """
        链表长度
        :return:
        """

        if self.is_empty():
            return 0
        n = 1
        cur = self._head
        while cur != self._head:
            cur = cur.naxt
            n += 1
        return 1


接着我们再实现涉及所有节点的一些操作:遍历节点、是否存在指定节点。

class SinCycLinkedlist:

    def __init__(self):
        self._head = None

    def is_empty(self):
        """
        是否为空链表
        :return:
        """

        return None == self._head

    @property
    def length(self):
        """
        链表长度
        :return:
        """

        if self.is_empty():
            return 0
        n = 1
        cur = self._head
        while cur != self._head:
            cur = cur.naxt
            n += 1
        return n

    def ergodic(self):
        """
        遍历所有节点
        :return:
        """

        if self.is_empty():
            raise ValueError('error null')
        cur = self._head
        print(cur.item)
        while cur != self._head:
            cur = cur.naxt
            print(cur.item)

    def search(self, item):
        """查找节点是否存在"""
        if self.is_empty():
            raise ValueError('error null')
        cur = self._head
        if cur.item == item:
            return True
        while cur != self._head:
            if cur.item == item:
                return True
        return False


这些基本操作和单向链表基本一致,但是不同的是判断最后一个元素的标志不再是next==None而是next指向了头部指向的节点,这就是最后一个节点。

接下来实现操作节点增减的头部添加,尾部添加,任意位置添加、删除操作。

class Node:
    def __init__(self, item):
        self.item = item  # 该节点值
        self.next = None   #  连接一下一个节点


class SinCycLinkedlist:

    def __init__(self):
        self._head = None

    def is_empty(self):
        """
        是否为空链表
        :return:
        "
""
        return None == self._head

    @property
    def length(self):
        """
        链表长度
        :return:
        "
""
        if self.is_empty():
            return 0
        n = 1
        cur = self._head
        while cur.next != self._head:
            cur = cur.next
            n += 1
        return n

    def ergodic(self):
        """
        遍历所有节点
        :return:
        "
""
        if self.is_empty():
            raise ValueError('error null')
        cur = self._head
        print(cur.item)
        while cur.next != self._head:
            cur = cur.next
            print(cur.item)

    def search(self, item):
        """查找节点是否存在"""
        if self.is_empty():
            raise ValueError('error null')
        cur = self._head
        if cur.item == item:
            return True
        while cur != self._head:
            if cur.item == item:
                return True
        return False

    def add(self, item):
        """
        头部添加
        :param item:
        :return:
        "
""
        node = Node(item)
        if self.is_empty():
            self._head = node
            node.next = node
        else:
            cur = self._head
            while cur.next != self._head:
                cur = cur.next
            node.next = self._head
            self._head = node
            cur.next = node

    def append(self, item):
        """
        尾部添加节点
        :param item:
        :return:
        "
""
        node = Node(item)
        if self.is_empty():
            self.add(item)
        else:
            cur = self._head
            while cur.next != self._head:
                cur = cur.next
            cur.next = node
            node.next = self._head

    def insert(self, index, item):
        """
        任意位置插入节点
        :param item:
        :return:
        "
""
        node = Node(item)
        if index+1 >= self.length:
            self.append(item)
        elif index == 0:
            self.add(item)
        else:
            cur = self._head
            n = 1
            while cur.next != self._head:
                pre = cur
                cur = cur.next
                if n == index:
                    break
                n += 1
            pre.next = node
            node.next = cur

    def delete(self, item):
        """
        删除元素
        :param item:
        :return:
        "
""
        # 若链表为空,则直接返回
        if self.is_empty():
            return
        cur = self._head
        pre = None
        # 若头节点的元素就是要查找的元素item
        if cur.item == item:
            # 如果链表不止一个节点
            if cur.next != self._head:
                while cur.next != self._head:
                    cur = cur.next
                cur.next = self._head.next
                self._head = self._head.next
            else:
                # 链表只有一个节点
                self._head = None
        else:
            pre = self._head
            # 第一个节点不是要删除的
            while cur.next != self._head:
                if cur.item == item:
                    pre.next = cur.next
                    return
                else:
                    pre = cur
                    cur = cur.next
            # cur 指向尾节点
            if cur.item == item:
                pre.next = cur.next



相关文章
|
4月前
|
测试技术 开发者 Python
Python单元测试入门:3个核心断言方法,帮你快速定位代码bug
本文介绍Python单元测试基础,详解`unittest`框架中的三大核心断言方法:`assertEqual`验证值相等,`assertTrue`和`assertFalse`判断条件真假。通过实例演示其用法,帮助开发者自动化检测代码逻辑,提升测试效率与可靠性。
439 1
|
5月前
|
机器学习/深度学习 数据采集 数据挖掘
基于 GARCH -LSTM 模型的混合方法进行时间序列预测研究(Python代码实现)
基于 GARCH -LSTM 模型的混合方法进行时间序列预测研究(Python代码实现)
203 2
|
5月前
|
调度 Python
微电网两阶段鲁棒优化经济调度方法(Python代码实现)
微电网两阶段鲁棒优化经济调度方法(Python代码实现)
170 0
|
4月前
|
人工智能 数据安全/隐私保护 异构计算
桌面版exe安装和Python命令行安装2种方法详细讲解图片去水印AI源码私有化部署Lama-Cleaner安装使用方法-优雅草卓伊凡
桌面版exe安装和Python命令行安装2种方法详细讲解图片去水印AI源码私有化部署Lama-Cleaner安装使用方法-优雅草卓伊凡
594 8
桌面版exe安装和Python命令行安装2种方法详细讲解图片去水印AI源码私有化部署Lama-Cleaner安装使用方法-优雅草卓伊凡
|
5月前
|
机器学习/深度学习 数据采集 算法
【CNN-BiLSTM-attention】基于高斯混合模型聚类的风电场短期功率预测方法(Python&matlab代码实现)
【CNN-BiLSTM-attention】基于高斯混合模型聚类的风电场短期功率预测方法(Python&matlab代码实现)
329 4
|
4月前
|
算法 调度 决策智能
【两阶段鲁棒优化】利用列-约束生成方法求解两阶段鲁棒优化问题(Python代码实现)
【两阶段鲁棒优化】利用列-约束生成方法求解两阶段鲁棒优化问题(Python代码实现)
135 0
|
5月前
|
机器学习/深度学习 数据采集 TensorFlow
基于CNN-GRU-Attention混合神经网络的负荷预测方法(Python代码实现)
基于CNN-GRU-Attention混合神经网络的负荷预测方法(Python代码实现)
254 0
|
SQL JSON C语言
Python中字符串的三种定义方法
Python中字符串的三种定义方法
649 2
|
Python
Python面向对象、类的抽象、类的定义、类名遵循大驼峰的命名规范创建对象、类外部添加和获取对象属性、类内部操作属性魔法方法__init__()__str__()__del__()__repr__()
面向对象和面向过程,是两种编程思想. 编程思想是指对待同一个问题,解决问题的套路方式.面向过程: 注重的过程,实现的细节.亲力亲为.面向对象: 关注的是结果, 偷懒.类和对象,是面向对象中非常重要的两个概念object 是所有的类基类,即最初始的类class 类名(object): 类中的代码PEP8代码规范:类定义的前后,需要两个空行 创建的对象地址值都不一样如dog和dog1的地址就不一样,dog的地址为2378043254528dog1的地址为2378044849840 8.类内部操作属性 sel
504 1
Python面向对象、类的抽象、类的定义、类名遵循大驼峰的命名规范创建对象、类外部添加和获取对象属性、类内部操作属性魔法方法__init__()__str__()__del__()__repr__()

推荐镜像

更多