①利用列表实现栈,将列表末尾作为栈顶
#列表尾部是栈的顶端 class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[len(self.items) - 1] def size(self): return len(self.items) # s =Stack() # print(s.isEmpty()) # # s.push(1) # s.push('dog') # print(s.peek()) # print(s.size()) # print(s.isEmpty()) # print(s.pop()) # print(s.size())
②利用列表实现栈,将列表头部作为栈顶
#列表头部是栈的顶端 class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def pop(self): return self.items.pop(0) def push(self,item): self.items.insert(0,item) def peek(self): return self.items[0] def size(self): return len(self.items)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)