class Node(object):
"""节点类"""
def __init__(self, item):
# 记录节点的内容
self.item = item
# 记录下一个节点
self.next = None
class SingleCycLinkList(object):
"""链表类"""
def __init__(self):
# 记录头节点
self.__head = None
def is_empty(self):
"""链表是否为空"""
# 判断头节点是否为空
return self.__head is None
def length(self):
"""链表长度"""
if self.is_empty():
return 0
# 定义游标变量,从头往后遍历
cur = self.__head
# 定义变量,统计个数
count = 1
while cur.next is not self.__head:
count += 1
# 游标往后移动
cur = cur.next
return count
def travel(self):
"""遍历整个链表"""
if self.is_empty():
return
# 定义游标变量,从头往后遍历
cur = self.__head
# 输出头节点内容
print(cur.item, end=" ")
# 输出第二个节点到尾节点
while cur.next is not self.__head:
# 游标往后移动
cur = cur.next
# 输出当前节点内容
print(cur.item,end=" ")
print()
def add(self, item):
"""链表头部添加元素"""
node = Node(item)
if self.is_empty():
self.__head = node
# 如果只有一个节点,自己指向自己
node.next = node
return
# 找到尾节点
cur = self.__head
while cur.next is not self.__head:
# 游标往后移动
cur = cur.next
# 循环结束后,cur指向的是尾节点
node.next = self.__head
self.__head = node
# 让尾节点指向新的头
cur.next = self.__head
def append(self, item):
"""链表尾部添加元素"""
# 判断链表是否为空
if self.is_empty():
self.add(item)
return
# 1、遍历找到尾节点
# 定义游标变量,从头往后遍历
cur = self.__head
while cur.next is not self.__head:
# 游标往后移动
cur = cur.next
# 当while循环结束,cur指向的是尾节点
# 2、让尾节点指向新节点
node = Node(item)
cur.next = node
# 让尾节点指向头节点
node.next = self.__head
def insert(self, pos, item):
"""指定位置添加元素"""
# 健壮性
if pos <= 0:
self.add(item)
elif pos > (self.length() - 1):
self.append(item)
else:
# 1、找到pos前一个位置的节点
cur = self.__head
# 定义下标变量
index = 0
while index < (pos - 1):
# 游标往后移动
index += 1
cur = cur.next
# while 循环结束 cur指向的就是pos前一个位置的节点
# 2、插入新节点
node = Node(item)
# 让新节点指向pos位置的节点
node.next = cur.next
# pos前一个位置的节点指向新节点
cur.next = node
def remove(self, item):
"""删除节点"""
if self.is_empty():
return
# 1、找到要删除的节点的前置节点
cur = self.__head
# 记录当前游标的前置节点
pre = None
while cur.next is not self.__head:
if cur.item == item:
# 2、删除当前节点
# 如果pre为none,证明删除的是头节点
if pre is None:
# 找到尾节点,尾节点指向新的头
temp = self.__head
while temp.next is not self.__head:
temp = temp.next
# while循环结束,temp指向的是尾节点
self.__head = cur.next
temp.next = self.__head
else:
pre.next = cur.next
return
pre = cur
cur = cur.next
# while循环处理不了尾节点,循环后再处理
if cur.item == item:
# 如果pre为none,链表只有一个节点,删除的是头结点
if pre is None:
self.__head = None
else:
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 is not self.__head:
cur = cur.next
if cur.item == item:
return True
return False