备注:约定以栈的头为栈顶
1 """
2 栈的链式存储
3 重点代码
4 """
5
6 # 自定义栈异常
7 class StackError(Exception):
8 pass
9
10 # 创建结点类
11 class Node(object):
12 def __init__(self, val, next=None):
13 self.val = val # 有用数据
14 self.next = next
15
16 class LStack:
17 def __init__(self):
18 # 标记栈顶位置
19 self._top = None
20
21 def is_empty(self):
22 return self._top is None
23
24 #入栈
25 def push(self,elem):
26 self._top = Node(elem,self._top)
27
28 #弹栈
29 def pop(self):
30 if self._top is None:
31 raise StackError("stack is empty")
32 p = self._top
33 self._top = p.next
34 return p.val
35
36 # 查看栈顶元素值
37 def top(self):
38 if self._top is None:
39 raise StackError("stack is empty")
40 return self._top.val
41
42 if __name__ == "__main__":
43 st = LStack()
44 print(st.is_empty()) # 判断是否为空
45 st.push(10)
46 st.push(20)
47 print(st.top()) # 获取栈顶元素值
48 st.push(30)
49 while not st.is_empty():
50 print(st.pop())