1. 栈简介
- python栈是一种数据结构,它遵循后进先出(LIFO)原则。可以通过使用push()和pop()方法将元素添加到栈中或从栈中删除元素
- 使用场景:浏览器页面打开—返回
2. 栈实现
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.insert(0, item)
def pop(self):
self.items.pop(0)
def is_empty(self):
return self.items == []
def size(self):
return len(self.items)
if __name__ == '__main__':
stack = Stack()
stack.push('元素1')
stack.push('元素2')
stack.push('元素3')
print(stack.items). # ['元素3', '元素2', '元素1']
stack.pop()
print(stack.items) # ['元素2', '元素1']