本文最后更新于2022年11月09日,已超过907天没有更新。如果文章内容或图片资源失效,请留言反馈,我会及时处理,谢谢!
您阅读这篇文章共耗时:
单向循环链表(首尾相连)
单链表的一个变形是单向循环链表单向循环链表,链表中最后一个节点的next域不再为None,而是指向链表的头节点。
ps:关于类加上object----object类似于一个基础类,协商相当于自定义的类继承了object的功能单向循环链表,在里即使不写,也默认加载obiect。
链表里:
a=b表示将a指向b
代码实现与详解(注释内)
class Node(object): """节点""" def __init__(self, item): self.item = item self.next = None class SinCycLinkedlist(object): """单向循环链表""" def __init__(self): self._head = None def is_empty(self): """判断链表是否为空""" return self._head == None def length(self): """返回链表的长度""" # 如果链表为空,返回长度0 if self.is_empty(): return 0 count = 1#此处区别于单链表,单链表此处count=0 cur = self._head while cur.next != self._head:#尾部等于头部 count += 1 cur = cur.next return count def travel(self): """遍历链表""" if self.is_empty(): return cur = self._head print cur.item, while cur.next != self._head: cur = cur.next print cur.item, print "" def add(self, item): """头部添加节点""" node = Node(item)#需要加具体值元素的时候,开始实例化节点,然后加入链表结构 if self.is_empty(): self._head = node node.next = self._head else: #添加的节点指向_head node.next = self._head # 移到链表尾部,将尾部节点的next指向node cur = self._head while cur.next != self._head: cur = cur.next cur.next = node #_head指向添加node的 self._head = node def append(self, item): """尾部添加节点""" node = Node(item) if self.is_empty(): self._head = node node.next = self._head else: # 移到链表尾部 cur = self._head while cur.next != self._head: cur = cur.next # 将尾节点指向node cur.next = node # 将node指向头节点_head node.next = self._head def insert(self, pos, item): """在指定位置添加节点""" if pos (self.length()-1): self.append(item) else: node = Node(item) cur = self._head count = 0 # 移动到指定位置的前一个位置 while count [1]: https://xuan.ddwoo.top/index.php/archives/155/ [2]: https://xuan.ddwoo.top/index.php/archives/154/ 本文来自投稿,不代表本站立场,如若转载,请注明出处:http://xuan.ddwoo.top/index.php/archives/159/