数据结构之 栈 (Python 版)
-- 利用线性表实现栈
栈的特性: 后进先出
- 基于顺序表实现栈
class SStack(): '''
基于顺序表 实现的 栈类
''' def __init__(self):
self._elems = [] def is_empty():
return self._elems == [] def top(self):
if self._elems == [] :
raise StackUnderflow(" in Stack.top . ")
return self._elems[-1] def push(self,elem):
self._elems.append(elem) def pop(self):
if self._elems == [] :
raise StackUnderflow(" in Stack.pop .")
return self._elems.pop() - 基于链表技术实现栈
class LStack(): '''
基于链接表技术实现的栈类, 使用 LNode 作为节点
''' def __init__(self):
self._top = None def is_empty(self):
return self._top is None def top(self):
if self._top is None :
raise StackUnderflow(" in LStack.top .")
return self._top.elem def push(self,elem):
self._top = LNode(elem,self._top) def pop(slef):
if self._top is None :
raise StackUnderflow(" in Stack.pop . ")
p = self._top
slef._top = p.next
return p.elem