Queue 队列
性质:先入先出FIFO
在FIFO数据结构中,将首先处理添加到其中的第一个元素。队列是典型的 FIFO 数据结构。
- 插入(insert)操作也称作入队(enqueue),新元素始终被添加在队列的末尾。
- 删除(delete)操作也被称为出队(dequeue)。 你只能移除第一个元素。
队列的实现(python)——列表list实现
class Queue:
def __init__(self):
self.items=[]
def isEmpty(self):
return self.items==[]
def enqueue(self,item):
self.items.insert(0,item)
def dequeue(self):
return self.items.pop()
def size(self):
return len(self.items)
循环队列的实现
代码
class MyCircularQueue:
def __init__(self, k: int):
"""
Initialize your data structure here. Set the size of the queue to be k.
"""
self.item = [-1 for _ in range(k)]
self.maxsize = k
self.size = 0
self.font = -1
self.rear = 0
def enQueue(self, value: int) -> bool:
"""
Insert an element into the circular queue. Return true if the operation is successful.
"""
if self.isFull():
return False
else:
self.item[self.rear] = value
self.rear = (self.rear+1)%self.maxsize
self.size += 1
return True
def deQueue(self) -> bool:
"""
Delete an element from the circular queue. Return true if the operation is successful.
"""
if self.isEmpty():
return False
else:
self.font = (self.font+1)%self.maxsize
self.size -= 1
return True
def Front(self) -> int:
"""
Get the front item from the queue.
"""
if not self.isEmpty():
return self.item[self.font+1]
else:
return -1
def Rear(self) -> int:
"""
Get the last item from the queue.
"""
if not self.isEmpty():
return self.item[self.rear-1]
else:
return -1
def isEmpty(self) -> bool:
"""
Checks whether the circular queue is empty or not.
"""
return self.size == 0
def isFull(self) -> bool:
"""
Checks whether the circular queue is full or not.
"""
return self.size == self.maxsize
# Your MyCircularQueue object will be instantiated and called as such:
# obj = MyCircularQueue(k)
# param_1 = obj.enQueue(value)
# param_2 = obj.deQueue()
# param_3 = obj.Front()
# param_4 = obj.Rear()
# param_5 = obj.isEmpty()
# param_6 = obj.isFull()
代码解释
self.font
:代表循环队列列首的前一个位置,也就是self.font=real_font-1
self.rear
:代表循环队列列尾的后一个位置,也就是self.rear=real_rear+1
self.size
:判断队列的空满,当然也可以用下列方式判断队列的空满(real_rear+1)%maxsize=real_font
,也就是(self.rear)%self.maxsize==self.font+1
:再添加一个元素之后,队首self.font+1
和队尾(self.rear)%self.maxsize
重合(real_font+1)%maxsize=real_rear
,也就是(self.font+2)%self.maxsize==self.rear-1
:再删除一个元素之后,队首(self.font+2)%self.maxsize
和队尾self.rear-1
重合
图示
队列Queue与广度优先搜索BFS
#->功能:广度优先搜索算法
#->传入参数:g(图),start(起始节点)
def bfs(g,start):
#当前顶点的distance predecessor的设置
start.setDistance(0)
start.setPred(None)
#新建队列,存储顶点
vertQueue = Queue()
#当前节点进队
vertQueue.enqueue(start)
while (vertQueue.size() > 0):
currentVert = vertQueue.dequeue() #取队首为当前顶点
for nbr in currentVert.getConnections()[0]: #遍历当前顶点的邻接顶点
if nbr.getColor() == \'white\': #邻接顶点白色(未遍历)
nbr.setColor(\'gray\') #遍历过了
nbr.setDistance(currentVert.getDistance()+1) #当前顶点的距离加1作为该遍历节点的距离
nbr.setPred(currentVert) #设置前驱
vertQueue.enqueue(nbr) #邻接节点入队
currentVert.setColor(\'black\') #当前节点全部遍历