[Python数据结构] 使用List实现Stack
1. Stack
堆栈
(
Stack
)又称为
栈
或
堆叠
,是计算机科学
中一种特殊的串列形式的抽象数据类型(ADT)
,其特殊之处在于只能允许在阵列的一端
进行加入数据
和删除数据,并且执行顺序应按照
后进先出(LIFO)
的原则。
2. Stack ADT
堆栈是一种抽象数据类型,其实例S需要支持两种方法:
1)S.push(e) : add element e to the top of stack S
2)S.pop( ) : remove and return the top element from the stack S
另外,为了方便使用,我们还定义了以下方法:
3)S.top() : return the top element from the stack S, but not remove it
4)S.is_empty() : Return True if the stack is empty
5)len(S) : Return the number of elements in the stack
3. Implementing a Stack using a List
class Empty(Exception):
"""Error attempting to access an element from an empty container"""
pass
class OverFlow(Exception):
"""Error attempting to push an element to an full container"""
pass
class ArrayStack():
"""LIFO Stack implementation using a Python list as underlying storage"""
def __init__(self, n):
"""Create an empty stack."""
self.data = []
self.maxLen = n # n : an integer that represent the max elements capacity of the stack
def __len__(self):
"""Return the number of elements in the stack"""
return len(self.data)
def is_empty(self):
"""Return True if the stack is empty"""
return len(self.data) == 0
def is_full(self):
"""Return True if the stack is full"""
return len(self.data) == self.maxLen
def push(self, e):
"""Add element e to the top of the stack
Raise Empty exception if the stack is full"""
if self.is_full():
raise OverFlow('Stack is full')
return self.data.append(e)
def top(self):
"""Return the element at the top of the stack, but not move it.
Raise Empty exception if the stack is empty"""
if self.is_empty():
raise Empty('Stack is empty')
return self.data[-1]
def pop(self):
"""Return the element at the top of the stack, meanwhile move it.
Raise Empty exception if the stack is empty"""
if self.is_empty():
raise Empty('Stack is empty')
return self.data.pop()
执行结果:
s = ArrayStack(10)
l = np.random.randint(0, 10, size=(10, ))
for i in l:
s.push(i)
s.data
[6, 8, 7, 4, 2, 3, 4, 1, 5, 8]
s.pop()
8
s.data
[6, 8, 7, 4, 2, 3, 4, 1, 5]
s.top()
5
s.data
[6, 8, 7, 4, 2, 3, 4, 1, 5]