# 完成双向循环链表的判空、尾插、遍历、尾删
class Node:def __init__(self, value):self.value = valueself.next = Noneself.prev = None
class Linklist:def __init__(self,node=None):self.head = nodeself.size = 0def is_empty(self):return self.size == 0def add_tail(self,value):node = Node(value)if self.is_empty():self.head = nodenode.next = nodenode.prev = nodeelse:cur = self.headwhile cur.next != self.head:cur = cur.nextcur.next = nodenode.prev = curnode.next = self.headself.head.prev = nodeself.size += 1def del_tail(self):pre=Noneif self.is_empty():print("链表为空,删除失败")else:if self.size == 1:self.head = Noneself.size -= 1returnelse:cur = self.headwhile cur.next !=self.head:pre=curcur=cur.nextpre.next=self.headself.head.prev=preself.size -= 1def show(self):if self.is_empty():print("链表为空")else:cur = self.headwhile cur.next != self.head:print(cur.value,end=" ")cur = cur.nextprint(cur.value)
if __name__ == "__main__":linklist = Linklist()linklist.add_tail(1)linklist.add_tail(2)linklist.add_tail(3)linklist.add_tail(4)linklist.add_tail(5)linklist.show()linklist.del_tail()linklist.show()linklist.del_tail()linklist.show()linklist.del_tail()linklist.show()linklist.del_tail()linklist.show()linklist.del_tail()linklist.show()
# 完成链式栈的:
# - 创建一个空栈
# - 添加数据
# - 遍历栈
# - 弹出栈顶元素(删除)
# - 返回栈顶元素
# - 判空
# - 栈的大小
class Node:def __init__(self,value):self.data = valueself.next = None
class Stack:def __init__(self,node=None):self.head = node#判空def is_empty(self):return self.head is Nonedef push(self,value):node = Node(value)if self.is_empty():self.head = nodeelse:node.next = self.headself.head = nodedef pop(self):if self.is_empty():print("栈为空")returnelse:self.head = self.head.nextdef show(self):if self.is_empty():print("栈为空")returnelse:cur = self.headwhile cur:print(cur.data,end=" ")cur = cur.nextprint()def size(self):cur = self.headcount = 0while cur:count += 1cur = cur.nextreturn countdef top(self):if self.is_empty():print("栈为空")returnelse:return self.head.dataif __name__ == "__main__":s = Stack()s.push(1)s.push(2)s.push(3)s.push(4)s.push(5)s.show()print(s.top())print(s.size())s.pop()s.pop()s.pop()s.show()