PHP前端开发

【python学习】单向循环链表的python语法实现

百变鹏仔 1个月前 (01-23) #Python
文章标签 语法

之前的学习中都是用C语言编写的链表实现,今天小编将带大家一起来学习用python编写单向循环链表。

链表

链表(Linked list)是一种常见的基础数据结构,是⼀种线性表,但是不像顺序表一样连续存储数据,是在每个节点(数据存储单元)存放下一个节点的位置信息(即地址)。

  Python

          单向循环链表

单链表的一个变形是单向循环链表,链表中最后一个节点的next域不再为None,而是指向链表的头节点。

语法实现:

class Node(object):    """结点类"""    def __init__(self, item):        self.item = item        self.next = Noneclass CyclesSingleLinkList():    """单向循环链表"""    def __init__(self, node=None):        self.__head = node    def is_empty(self):        """链表是否为空        :return 如果链表为空 返回真        """        return self.__head is None    def length(self):        """链表长度"""        # 如果是空链表        if self.is_empty():            return 0        cur = self.__head        count = 1        while cur.next != self.__head:            count += 1            cur = cur.next        return count    def travel(self):        """遍历整个链表"""        if self.is_empty():            print("")            return        cur = self.__head        while cur.next != self.__head:            print(cur.item, end=" ")            cur = cur.next        # 从循环退出,cur指向的是尾结点        print(cur.item)    def add(self, item):        """链表头部添加元素        :param item: 要保存的具体数据        """        node = Node(item)        if self.is_empty():            self.__head = node            node.next = node        # 寻找尾结点        cur = self.__head        while cur.next != self.__head:            cur = cur.next        # 从循环中退出,cur指向尾结点        node.next = self.__head        self.__head = node        cur.next = self.__head    def append(self, item):        """链表尾部添加元素"""        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            #退出循环的时候,cur指向尾结点            cur.next = node            node.next = self.__head    def insert(self, pos, item):        """指定位置添加元素"""        # 在头部添加元素        if pos = self.length():            self.append(item)        else:            cur = self.__head            count = 0            while count <p>  【课程推荐:<a href="http://www.php.cn/course/list/30.html" target="_self">Python视频教程</a>】</p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/00968c3c2c15" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">Python免费学习笔记(深入)</a>”;</p><link href="https://csdnimg.cn/release/phoenix/mdeditor/markdown_views-258a4616f7.css" rel="stylesheet"><!-- flowchart 箭头图标 勿删 --><svg xmlns="http://www.w3.org/2000/svg" style="display: none;"><path stroke-linecap="round" d="M5,0 0,2.5 5,5z" id="raphael-marker-block" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></path></svg><p>		</p>