python栈的顺序存储结构
作者:互联网
"""
栈 (sstack)
栈的顺序存储结构
"""
# 基于列表实现顺序栈
# 自定义栈异常
class StackError(Exception):
pass
class SStack:
def __init__(self):
# 约定列表的最后一个元素为栈顶元素
self._elems = []
# 显示栈顶元素
def top(self):
if not self._elems:
raise StackError("stack is empty")
return self._elems[-1]
# 判断栈是否为空
def is_empty(self):
return self._elems == []
# 入栈
def push(self,elem):
self._elems.append(elem)
# 出栈
def pop(self):
if not self._elems:
raise StackError("stack is empty")
return self._elems.pop()
if __name__ == "__main__":
st = SStack() #初始化栈
# print(st.top())
print(st.is_empty())
st.push(10)
st.push(30)
st.push(20)
print(st.top())
# while not st.is_empty():
# print(st.pop())
#
st.pop()
print(st.top())
标签:__,python,self,elems,st,._,print,顺序存储,结构 来源: https://blog.csdn.net/wu_song_da_hu/article/details/97492299