循环队列是 队列的一种特殊形式。首先介绍队列,然后引申出循环队列。
队列又称为“先进先出”(FIFO)线性表
限定插入操作只能在队尾进行,而删除操作只能在队首进行
对于顺序队列:
空队列 head = tail
当插入新元素到队尾时,tail加1
当删除队首元素时,head加1,上图如果把C也删掉,那么就 head = tail 了
tail 始终指向队列元素的下一个位置
对应的操作:
队空:head=tail
求队长:tail - head
入队:新元素按 tail 指示位置加入,再将队尾指针加1 ,即 tail = tail + 1
出队:将head指示的元素取出,再将队头指针加1,即head = head + 1
循环队列:
入队时,tail指针变化:
tail= (tail+1)%maxsize
出队时,head指针变化:
head=( head +1)%maxsize
思路:
双指针法,start指向目前队列的头,end指向目前队列的尾,两者初始值都为-1,
插入元素时,如果是第一个元素,那么start end 都变成 0
如果不是第一个元素,队尾延长,end + 1,注意是循环的队列所以需要%最大长度
如果队列已经满了,就返回False
删除元素时,如果是最后一个元素,那么start end 都变成-1
如果不是最后一个元素,队头出队,start + 1, 同样注意循环
如果队列是空的,就返回Flase
返回队头,如果有队头,直接输出start指向的元素;否则按题目要求输出-1
返回队尾,如果有队尾,直接输出end指向的元素;否则按题目要求输出-1
检查是否Full,如果end的下一位是start,就代表已经full
检查是否Empty,如果start 和end 都是-1,就代表已经empty
class MyCircularQueue(object):
def __init__(self, k):
"""
Initialize your data structure here. Set the size of the queue to be k.
:type k: int
"""
self.queue = [""] * k
self.max_length = k
self.start = -1
self.end = -1
def enQueue(self, value):
"""
Insert an element into the circular queue. Return true if the operation is successful.
:type value: int
:rtype: bool
"""
if not self.isFull():
if self.start == -1:
self.start = 0
self.end = (self.end + 1) % self.max_length
self.queue[self.end] = value
return True
else:
return False
def deQueue(self):
"""
Delete an element from the circular queue. Return true if the operation is successful.
:rtype: bool
"""
if not self.isEmpty():
if self.start == self.end: # the last element
self.start, self.end = -1, -1
# self.end = -1
else:
self.start = (self.start + 1) % self.max_length
return True
else:
return False
def Front(self):
"""
Get the front item from the queue.
:rtype: int
"""
if self.isEmpty():
return -1
else:
return self.queue[self.start]
def Rear(self):
"""
Get the last item from the queue.
:rtype: int
"""
if self.isEmpty() :
return -1
else:
return self.queue[self.end]
def isEmpty(self):
"""
Checks whether the circular queue is empty or not.
:rtype: bool
"""
return self.start == -1 and self.end == -1
def isFull(self):
"""
Checks whether the circular queue is full or not.
:rtype: bool
"""
return (self.end + 1) % self.max_length == self.start