class LNode:
def __init__(self, elem, next_=None):
self.elem = elem
self.next = next_
class LinkedListUnderUnderflow(ValueError):
pass
class LCList:
def __init__(self) -> None:
self.rear = None
# 前端插入
def prepend(self, elem):
p = LNode(elem)
if self.rear is None:
p.next = p
self.rear = p
else:
p.next = self.rear.next
self.rear.next = p
# 后端插入
def append(self, elem):
self.prepend(elem)
self.rear = self.rear.next
# 生成列表
def generate_list(self):
temp_list = []
p = self.rear.next
if self.rear is None:
return temp_list
while True:
temp_list.append(p.elem)
if p is self.rear:
return temp_list
p = p.next
# 前端弹出
def pop(self):
if self.rear is None:
raise LinkedListUnderUnderflow("in pop")
p = self.rear.next
if self.rear == p:
self.rear = None
else:
self.rear.next = p.next
return p.elem
# 后端弹出
def pop_last(self):
if self.rear is None:
raise LinkedListUnderUnderflow("in pop_last")
p = self.rear.next
e = self.rear.elem
if self.rear == p:
self.rear = None
else:
while p.next is not self.rear:
p = p.next
p.next = self.rear.next
self.rear = p
return e
if __name__ == '__main__':
lclist = LCList()
for i in range(1, 11):
lclist.append(i)
print(lclist.generate_list())
lclist.pop()
print(lclist.generate_list())
lclist.pop_last()
print(lclist.generate_list())
Python 数据结构的循环单链表实现
最新推荐文章于 2022-04-08 14:49:15 发布