python 栈和队列(使用list实现)
来源:互联网 发布:龙发装修 知乎 编辑:程序博客网 时间:2024/05/21 09:21
5.1.1. Using Lists as Stacks
The list methods make it very easy to use a list as a stack, where the last element added is the first element retrieved (“last-in, first-out”). To add an item to the top of the stack, use append()
. To retrieve an item from the top of the stack, use pop()
without an explicit index. For example:
>>> stack = [3, 4, 5]>>> stack.append(6)>>> stack.append(7)>>> stack[3, 4, 5, 6, 7]>>> stack.pop()7>>> stack[3, 4, 5, 6]>>> stack.pop()6>>> stack.pop()5>>> stack[3, 4]
5.1.2. Using Lists as Queues
It is also possible to use a list as a queue, where the first element added is the first element retrieved (“first-in, first-out”); however, lists are not efficient for this purpose. While appends and pops from the end of list are fast, doing inserts or pops from the beginning of a list is slow (because all of the other elements have to be shifted by one).
To implement a queue, use collections.deque
which was designed to have fast appends and pops from both ends. For example:
>>> from collections import deque>>> queue = deque(["Eric", "John", "Michael"])>>> queue.append("Terry") # Terry arrives>>> queue.append("Graham") # Graham arrives>>> queue.popleft() # The first to arrive now leaves'Eric'>>> queue.popleft() # The second to arrive now leaves'John'>>> queue # Remaining queue in order of arrivaldeque(['Michael', 'Terry', 'Graham'])
- python 栈和队列(使用list实现)
- [Python] 用list模拟栈和队列
- Python 使用list实现队列 (基于class, 包含迭代器)
- python实现栈和队列
- Python实现栈和队列
- python实现栈和队列--1(函数实现)
- python实现栈和队列--1(面向对象实现)
- python栈和队列的实现
- python实现stack(栈)和队列(queue)
- 用python实现栈和队列
- Python栈和队列的实现
- 栈和队列的python实现
- 【数据结构】队列和栈 Python 实现
- 集合_用List实现栈和队列
- Python使用list的append和pop方法创建堆栈和队列实例代码
- Python 使用list实现无边际优先队列 (基于class, 包含迭代器)
- python:(3)使用list和tuple
- python实现堆栈和队列
- linux之实现文件的压缩与解包
- github最后push一步出错
- 概率密度函数估计
- Spark核心作业调度和任务调度之DAGScheduler源码
- MySql 存储过程插入年月日
- python 栈和队列(使用list实现)
- STL库介绍
- Codeforces Round #417 (Div. 2) C. Sagheer and Nubian Market
- 竞赛题目-【USACO TRAINING】母亲的牛奶
- Spark 运行架构核心总结
- Linux-源码包安装软件
- mysql主从复制
- PowerPoint ppt 触发器 自定义动画 视频 音频 播放 停止
- layer中获取iFrame中的数据