栈(Python实现)

栈的数据类型描述

# 栈的抽象数据类型描述:
# ADT Stack:
#     Stack(self):     # 创建空栈
#         pass

#     is_empty(self):  # 判断栈是否为空
#         pass
    
#     push(self,elem): # 将元素elem压入栈顶
#         pass

#     pop(self):       # 弹出栈顶元素
#         pass

#     top(self):       # 获取栈顶元素,不删除
#         pass

栈的顺序表实现

### 自定义异常
class StackUnderflow(ValueError): # 栈下溢(空栈访问)
    pass


# 列表头作为栈底,列表尾作为栈顶
# 缺点:1、扩大存储需要做一次高代价的操作 2、需要完整的大块存储区域

### 使用list作为栈来使用
# lst = []
# lst.append()  # 压入
# lst[-1]  # 访问栈顶
# lst.pop()     # 弹出
class SStack: 
    def __init__(self):
        self._elems = []

    def is_empty(self):
        return self._elems == []

    def top(self):
        if self._elems == []:
            raise StackUnderflow("空栈异常:in SStack.top()")
        return self._elems[-1]

    def push(self,elem):
        self._elems.append(elem)

    def pop(self):
        if self._elems == []:
            raise StackUnderflow("空栈异常:in SStack.pop()")
        return self._elems.pop()

st1 = SStack()
st1.push(3)
st1.push(7)
st1.push(5)
while not st1.is_empty():
	print(st1.pop())

栈的链表实现

# 表头作为栈顶,表尾作为栈底
# 优点:解决了顺序表的缺点-->新增节点开销小,不需要连续锋内存
# 缺点:1、依赖解释器的存储管理   2、每个节点开销
class LNode: # 表节点
    def __init__(self, elem, _next=None):
        self.elem = elem
        self.next = _next


class LStack: #用LNode作为节点
    def __init__(self):
        self._top = None
    
    def is_empty(self):
        return self._top is None

    def push(self, elem):
        self._top = LNode(elem, self._top)

    def pop(self):
        if self._top is None:
            raise StackUnderflow("空栈异常:in LStack.pop()")
        p = self._top
        self._top = p.next
        return p.elem
    
    def top(self):
        if self._top is None:
            raise StackUnderflow("空栈异常:in LStack.top()")
        return self._top.elem

st2 = LStack()
st2.push(3)
st2.push(5)
st2.push(7)
while not st2.is_empty():
    print(st2.pop())

你可能感兴趣的:(算法与数据结构)