单向循环链表


# 单向循环链表结构的特征
# 节点对象: 数据域和向后引用域
# 尾部节点的向后引用域指向 头部

class Node(object):
def __init__(self, data):
# 数据域
self.data = data
# 引用域
self.next = None


class SgCyLinkList(object):
def __init__(self):
# 头节点
self.__head = None

# is_empty()链表是否为空
def is_empty(self):
return not self.__head

# length()链表长度
def length(self):
cur = self.__head
count = 0
if not cur:
return count
else:
while cur.next != self.__head:
count += 1
cur = cur.next
count += 1
return count

# travel()遍历链表
def travel(self):
cur = self.__head
if not cur:
return
while cur.next != self.__head:
print(cur.data, end=' --> ')
cur = cur.next
print(cur.data) # cur为尾节点时

# add(item)链表头部添加
def add(self, data):
node = Node(data)
if self.is_empty():
self.__head = node
node.next = self.__head
else:
cur = self.__head
while cur.next != self.__head:
cur = cur.next
node.next = self.__head
cur.next = node
self.__head = node

# append(item)链表尾部添加
def append(self, data):
cur = self.__head
if not cur:
self.add(data)
else:
while cur.next != self.__head:
cur = cur.next
node = Node(data)
cur.next = node
node.next = self.__head

# insert(index,data)指定位置添加元素
def insert(self, index, data):
if index <= 0:
self.add(data)
elif index >= self.length():
self.append(data)
else:
cur = self.__head
# 插入的位置是index, cur=cur.next偏移index-1次
for _ in range(index - 1):
cur = cur.next
node = Node(data)
node.next = cur.next
cur.next = node

# remove(item)删除节点
def remove(self, data):
cur = self.__head
if cur.data == data: # 删除头部 或 只有一个数据的链表
while cur.next != self.__head: # 找出尾节点
cur = cur.next
self.__head = None if self.length() == 1 else self.__head.next
cur.next = self.__head
else:
while cur.next != self.__head:
if cur.next.data == data:
cur.next = cur.next.next
break
cur = cur.next

# search(item)查找节点是否存在
def search(self, data):
cur = self.__head
if cur:
while cur.next != self.__head:
if cur.data == data:
return True
cur = cur.next
if cur.data == data:
return True
return False


if __name__ == '__main__':
sc = SgCyLinkList()
print(sc.length())
sc.append('aa')
for i in range(1, 11):
sc.add(i)
print('is_empty:', sc.is_empty())
sc.append('bb')
sc.travel()
print(sc.length())
print(sc.search('aa'))
print(sc.search('cc'))
sc.insert(0, 0)
sc.insert(-10, 0.1)
sc.insert(1000, 1000)
sc.travel()
sc.remove(0.1)
sc.remove(1000)
sc.remove(8)
sc.travel()
s = SgCyLinkList()
s.add(1)
s.travel()
s.remove(1)
s.travel()
print(s.is_empty())
posted @ 2021-02-07 22:56  涛子17180  阅读(64)  评论(0编辑  收藏  举报