head有数据,物理意义是next element in queue
tail没数据,物理意义是next available position
- poll: grab element at head, head++
- offer: put one element, tail++
当head==tail时,它要么是empty,要么满了,怎么知道是满了?解决方法:
维护一个size 当size==0, empty; size==array.length, full
public class BoundedQueue {
int head;
int tail;
int size;
Integer[] array;
public BoundedQueue(int cap) {
array = new Integer[cap];
head = tail = 0;
size = 0
}
public boolean offer(Integer ele) {
//1
if (size == array.length){
return false;
}
//2
array[tail] = ele;
tail = tail + 1 == array.length ? 0 : tail + 1;
size ++;
return true;
}
public Integer peek() {
if (size == 0) {
return null;
}
return array[head];
}
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public boolean isFull() {
return size == array.length;
}
}
如果不支持加一个size,就改变head和tail的物理意义,使得head+1==tail时是空,而head==tail时是满,也就是head指的格子不存数据,tail的格子也不存数据。
- poll: grab element at head+1, head++
- offer:put one element, tail++
class Solution(object):
def __init__(self, k):
"""
Initialize your data structure here. Set the size of the queue to be k.
:type k: int
"""
self.array = [None]*(k+1)
self.head = 0 #index of prev_to_the_next_available
self.tail = 1 #index of the first available spot
def enQueue(self, value):
"""
Insert an element into the circular queue. Return true if the operation is successful.
:type value: int
:rtype: bool
"""
if self.isFull():
return False
else:
self.array[self.tail]=value
self.tail=(self.tail+1)%len(self.array)
return True
def deQueue(self):
"""
Delete an element from the circular queue. Return true if the operation is successful.
:rtype: bool
"""
if self.isEmpty():
return False
else:
self.head=(self.head+1)%len(self.array)
return True
def Front(self):
"""
Get the front item from the queue.
:rtype: int
"""
return -1 if self.isEmpty() else self.array[self.head+1]
def Rear(self):
"""
Get the last item from the queue.
:rtype: int
"""
return -1 if self.isEmpty() else self.array[(self.tail-1+len(self.array))%len(self.array)]
def isEmpty(self):
"""
Checks whether the circular queue is empty or not.
:rtype: bool
"""
return self.tail-self.head==1
def isFull(self):
"""
Checks whether the circular queue is full or not.
:rtype: bool
"""
return self.tail==self.head