单向循环链表
Posted 月色真美丶
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了单向循环链表相关的知识,希望对你有一定的参考价值。
单向循环链表,相对于单向链表来说区别就是尾节点不再是指向None,而是指向头节点。
代码实现
# -*- coding = utf-8 -*- # @Author: Wchime # @time: 2023/1/20 15:31 # @file: 单向循环链表.py class Node(object): """单向链表节点""" def __init__(self, item): self.item = item self.next = None class SingleLoopList(object): """ 单向循环链表 """ def __init__(self, node=None): self.__link = node if node: node.next = node def is_empty(self): """ 判断链表是否为空 :return: """ return self.__link is None def get_length(self): """ 获取链表长度 循环链表最后节点next不是None值,而是第一个节点 :return: """ if self.is_empty(): return 0 else: cur = self.__link count = 1 while cur.next != self.__link: count += 1 cur = cur.next return count def append(self, item): """ 添加节点, 当链表不是空链表时,需要找到最后一个节点, 最后节点的判断的等于第一个节点 :param item: :return: """ node = Node(item) if self.is_empty(): self.__link = node node.next = node else: cur = self.__link while cur.next != self.__link: cur = cur.next cur.next = node node.next = self.__link def insert(self, index, item): """ 在指定位置插入节点 :param index: :param item: :return: """ # print(self.get_length()) if index == 0: node = Node(item) if self.is_empty(): self.__link = node node.next = node return cur = self.__link while cur.next != self.__link: cur = cur.next node.next = self.__link self.__link = node cur.next = node elif index > self.get_length()-1: self.append(item) else: pre = self.__link count = 0 while count < index - 1: count += 1 pre = pre.next node = Node(item) node.next = pre.next pre.next = node def remove(self, item): """ 根据值删除节点 :param item: :return: """ if self.is_empty(): return cur = self.__link pre = None while cur.next != self.__link: if cur.item == item: if cur == self.__link: # 头节点 rear = self.__link while rear.next != self.__link: rear = rear.next self.__link = cur.next rear.next = self.__link else: # 中间节点 pre.next = cur.next return else: pre = cur cur = cur.next # 尾节点 if cur.item == item: if cur == self.__link: self.__link = None else: pre.next = cur.next def search(self,item): """ 查找节点是否存在 :param item: :return: """ if self.is_empty(): return False cur = self.__link while cur.next != self.__link: if cur.item == item: return True else: cur = cur.next if cur.item == item: return True return False def travel(self): """ 链表遍历 :return: """ if self.is_empty(): return cur = self.__link while cur.next != self.__link: print(cur.item,end=" ") cur = cur.next print(cur.item) if __name__ == "__main__": singlelist = SingleLoopList() singlelist.append(1) singlelist.append(7) singlelist.append(5) singlelist.travel() singlelist.insert(1, 66) singlelist.travel() length = singlelist.get_length() print(length) print(singlelist.search(66)) singlelist.remove(66) singlelist.travel() print(singlelist.is_empty())
以上是关于单向循环链表的主要内容,如果未能解决你的问题,请参考以下文章