Python栈
FILO
使用list简单实现栈
表示方式
- 栈顶:list的最后一个元素[-1]
- 栈底:list的第一个元素[0]
出入栈
- 入栈:使用list.append()向列表最后一个位置添加一个元素
- 出栈:使用list.pop()弹出list的最后一个元素
class Stack:
def __init__(self):
self.items=[]
def push(self,item):
self.items.append(item)
def pop(self):
return self.items.pop()
def size(self):
return len(self.items)
def is_empty(self):
return self.items==[]
if __name__=="__main__":
stack=Stack()
stack.push("one")
stack.push("two")
print(stack.size())
print(stack.items)
stack.push("three")
stack.push("four")
print(stack.size())
print(stack.items)
print(stack.pop())
print(stack.size())
print(stack.items)