1、直接利用list的pop,push来实现
#!/usr/bin/env python3 # encoding: utf-8 class Stack: def __init__(self): self.items = [] def is_empty(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[-1] def size(self): return len(self.items) if __name__ == "__main__": s = Stack() print(s.is_empty()) s.push(4) s.push('dog') print(s.peek()) s.push(True) print(s.size()) print(s.is_empty()) s.push(8.4) print(s.pop()) print(s.pop()) print(s.size())
2、现在【0】存放底,同样利用list来实现。
#!/usr/bin/env python3 # encoding: utf-8 class Stack: def __init__(self): self.items = [] def is_empty(self): return self.items == [] def push(self, item): self.items.insert(0, item) def pop(self): return self.items.pop(0) def peek(self): return self.items[0] def size(self): return len(self.items)
s = Stack() print(s.is_empty()) s.push(4) s.push('dog') print(s.peek()) s.push(True) print(s.size()) print(s.is_empty()) s.push(8.4) print(s.pop()) print(s.pop()) print(s.size())