一、用列表模拟队列
队列支持先进先出的协议。与栈一样,也可以用列表来模拟队列,列表的哪一端是队头,哪一端是队尾,都无关紧要。最简单的策略就是使用列表的append方法来把项添加到队列的队尾,并且使用列表的pop(0)方法从列表的前面删除项并返回它。用这种方法的主要缺点是:所有其他的列表操作也可以操作这个栈,包括任意位置插入、替换和删除元素,这些操作就违反了队列作为一种抽象数据类型的本意。
1.1 队列方法
队列方法 | 作用 |
q.isEmpty() | 如果为空,返回True,否则返回False |
q.size() | 返回q中项目的数目 |
q.iter() | 从队头到队尾,访问q中的每一项 |
q.add(item) | 在q的队尾添加item |
q.pop() | 在q的队头删除一项,并返回该项。先验条件:q必须不为空,如果栈为空,将抛出KeyError |
q.peek() | 返回q的队头的项,先验条件:q必须不为空,如果栈为空,将抛出KeyError |
q.clear() | 将q清空 |
1.2用列表实现队列的代码:
#用列表实现队列
class Queue:
"""A list_based queue implementation."""
# Constructor
def __init__(self):
"""Sets the initial state of self,and the initial state is []"""
self.items = []
# Accessor methods
def iter(self):
"""Supports iteration over a view of self.
Visits items from bottom to top of queue."""
for i in range(len(self.items)):
yield self.items[i]
def isEmpty(self):
"""Returns True if len(self) == 0, or False otherwise."""
return len(self.items)==0
def peek(self):
"""
Returns the item at the top of the queue.
Precondition: the queue is not empty.
Raises: KeyError if the queue is empty."""
if self.isEmpty():
raise KeyError("The queue is empty.")
return self.items[0]
def size(self):
"""return the len(self)"""
return len(self.items)
# Mutator methods
def clear(self):
"""Makes self become empty."""
self.items = []
def add(self, item):
"""Adds item to the top of the queue."""
self.items.append(item)
def pop(self):
"""
Removes and returns the item at the top of the queue.
Precondition: the queue is not empty.
Raises: KeyError if the queue is empty.
Postcondition: the top item is removed from the queue."""
if self.isEmpty():
raise KeyError("The queue is empty.")
return self.items.pop(0)
1.3 测试队列
if __name__=='__main__':
q=Queue()
q.add(1)
q.add(2)
q.add(3)
print(list(q.iter())) #return:[1,2,3]
print(q.size()) #return:3
print(q.pop()) #return:1
print(q.peek()) #return:2
print(q.pop()) #return:2
print(q.pop()) #return:3
#若在此处添加一句:q.pop()或q.peek(),将报错:"The queue is empty."
q.clear()
print(q.isEmpty()) #return:True