python数据结构学习笔记-4-堆栈 队列

本文是关于Python中堆栈和队列的学习笔记,详细介绍了堆栈的后进先出(LIFO)原则及其在括号匹配和进制转换中的应用,以及队列的先进先出(FIFO)原则,并探讨了如何高效地使用list实现堆栈和队列,强调了通过阅读和模仿优质代码来提升编程技能的重要性。
摘要由CSDN通过智能技术生成

堆栈

堆栈是一个对象的集合,往集合中增加对象和从集合中移除对象必须符合后进先出原则(last-in, first-out() principle) 。在python中用list实现堆栈很方便,只要按照堆栈抽象数据类型做一个转换就可以了。


#堆栈
class Empty(Exception):
    """Error attempting to access an element from an empty container."""
    pass

class ArrayStack:
    """LIFO Stack implementation using a Python list as underlying storage."""
    
    def __init__(self):
        """Create an empty stack."""
        self._data = []
        
    def __len__(self):
        """Return the number of elements in teh stack."""
        return len(self._data)
    
    def is_empty(self):
        """Return True if the stack is empty."""
        return len(self._data) == 0
    
    def push(self, e):
        """Add element to the top of the stack."""
        self._data.append(e)
        
    def top(self):
        """Return (but do not remove) the element at the top of the stack.
        Raise Empty exception if the stack is empty.
        """
        if self.is_empty():
            raise Empty('Stack is empty')
        return self._data[-1]
    
    def pop(self):
        """Remove and return the element from the 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值