版权声明:本文博主原创,转载请注明出处,感谢您的合作! https://blog.csdn.net/Thanlon/article/details/89306577
使用Python列表作为存储实现一个栈 :
class ArrayStack:
def __init__(self):
# Create an empty stack
self.__data = []
def __len__(self):
# Return the number of elements in the stack
return len(self.__data)
def is_empty(self):
# Retutn True if the stack is empty
return len(self.__data) == 0
def push(self, e):
# Add an element to the top of stack
self.__data.append(e)
def pop(self):
# If element is empty ,it will raise Empty exception
if self.is_empty():
raise Empty('Stack is empty!')
# Remove and return the element from the top of the stack
return self.__data.pop()
def top(self):
# If element is empty ,it will raise Empty exception
if self.is_empty():
raise Empty('Stack is empty!')
# Return the last item in the list
return self.__data[-1]
class Empty(Exception):
pass