1 # coding:utf-8
2
3 class Stack(object):
4 """棧"""
5 def __init__(self):
6 self.__list = []
7
8 def push(self, item):
9 """添加一個新的元素item到棧頂"""
10 self.__list.append(item)
11
12 def pop(self):
13 """彈出棧頂元素"""
14 return self.__list.pop()
15
16 def peek(self):
17 """返回棧頂元素"""
18 if self.__list:
19 return self.__list[-1]
20 else:
21 return None
22
23 def is_empty(self):
24 """判斷棧是否爲空"""
25 return self.__list == []
26 # return not self.__list
27
28 def size(self):
29 """返回棧的元素個數"""
30 return len(self.__list)
31
32 if __name__ == "__main__":
33 s = Stack()
34 s.push(1)
35 s.push(2)
36 s.push(3)
37 s.push(4)
38 print(s.pop())
39 print(s.pop())
40 print(s.pop())