python 栈和队列(使用list实现)
2016-10-15 13:18
561 查看
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, useappend(). 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.dequewhich 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 arrival deque(['Michael', 'Terry', 'Graham'])
相关文章推荐
- python 栈和队列(使用list实现)
- python 栈和队列(使用list实现)
- python 栈和队列(使用list实现)
- Python 使用list实现队列 (基于class, 包含迭代器)
- python 栈和队列(使用list实现)
- python 栈和队列(使用list实现)
- Python 使用list实现无边际优先队列 (基于class, 包含迭代器)
- Python使用list的append和pop方法创建堆栈和队列实例代码
- Python 使用list实现简单的set
- leetcode_107. Binary Tree Level Order Traversal II 二叉树层次遍历,利用python的list特性实现队列功能
- [bigdata] 使用Redis队列来实现与机器无关的Job提交与执行 (python实现)
- 使用LinkedList实现队列
- Python中使用copy模块实现列表(list)拷贝
- Python 使用list实现堆栈 (基于class, 包含迭代器)
- Python 使用循环数组实现队列 (基于class, 包含迭代器)
- Java中使用LinkedList实现栈与队列
- python使用队列实现生产者消费者
- Python 使用list实现简单的集合set
- Python 使用list实现简单的堆栈
- Python 使用由单链表构建的数组实现有边际优先队列 (基于class, 包含迭代器)