<
>

python单向循环链表原理与实现方法示例

2020-06-25 08:08:35 来源:易采站长站 作者:易采站长站整理


node = Node(item)
cur = self.__head
count = 0
# 移动到指定位置的前一个位置
while count < (pos - 1):
count += 1
cur = cur.next
node.next = cur.next
cur.next = node
def remove(self, item):
"""删除一个节点"""
# 若链表为空,则直接返回
if self.is_empty():
return
# 将cur指向头节点
cur = self.__head
pre = None
while cur.next != self.__head:
if cur.item == item:
# 先判断此结点是否是头节点
if cur == self.__head:
# 头节点的情况
# 找尾节点
rear = self.__head
while rear.next != self.__head:
rear = rear.next
self.__head = cur.next
rear.next = self.__head
else:
# 中间节点
pre.next = cur.next
return
else:
pre = cur
cur = cur.next
# 退出循环,cur指向尾节点
if cur.item == item:
if cur == self.__head:
# 链表只有一个节点
self.__head = None
else:
# pre.next = cur.next
pre.next = self.__head
def search(self, item):
"""查找节点是否存在"""
if self.is_empty():
return False
cur = self.__head
if cur.item == item:
return True
while cur.next != self.__head:
cur = cur.next
if cur.item == item:
return True
return False
if __name__ == "__main__":
ll = SinCycLinkedlist()
ll.add(1)
ll.add(2)
ll.append(3)
ll.insert(2, 4)
ll.insert(4, 5)
ll.insert(0, 6)
print("length:", ll.length())
ll.travel()
print(ll.search(3))
print(ll.search(7))
ll.remove(1)
print("length:", ll.length())
ll.travel()

运行结果:

length: 6
6
2
1
4
3
5

True
False
length: 5
6
2
4
3
5

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数据结构与算法教程》、《Python加密解密算法与技巧总结》、《Python编码操作技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》

希望本文所述对大家Python程序设计有所帮助。

您可能感兴趣的文章:Python实现的单向循环链表功能示例Python双向循环链表实现方法分析Python数据结构与算法之链表定义与用法实例详解【单链表、循环链表】python双向链表原理与实现方法详解python单向链表的基本实现与使用方法【定义、遍历、添加、删除、查找等】python单链表实现代码实例浅谈Python单向链表的实现python双向链表实现实例代码python数据结构链表之单向链表(实例讲解)Python数据结构之翻转链表python实现单向链表详解Python二叉搜索树与双向链表转换实现方法

暂时禁止评论

微信扫一扫

易采站长站微信账号