题解 | #【模板】栈#
【模板】栈
https://www.nowcoder.com/practice/104ce248c2f04cfb986b92d0548cccbf
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() num = int(input()) for i in range(num): a = input() if a[0:4] == 'push': b = a.split(' ') s.push(int(b[1])) elif a=='pop': if s.isEmpty()==True: print('error') else: print(s.peek()) s.pop() elif a=='top': if s.isEmpty()==True: print('error') else: print(s.peek())
通过list实现了一个合理的stack