1.基本内容
- 队列也是一种线性结构
- 相比数组,队列对应的操作的数组的子集
- 只能从一端(队尾)添加元素,只能从另一端(队首取出元素)
- 先进先出的数据结构(FIFO)
2.队列的实现
2.1 数组队列
数组队列的出队的时间复杂度达到了O(n),这是比较高的时间。
2.2循环队列
- front==tail队列为空
- (tail+1)%c==front队列满
- capacity中,浪费一个空间
复杂度分析
package com.antfin.datastructure.queue;
public class LoopQueue<E> implements queue<E> {
private E [] data;
private int front,tail;
private int size;
public LoopQueue(int capacity){
data=(E[]) new Object[capacity+1];
front =0;
tail=0;
size=0;
}
public LoopQueue(){
this(10);
}
public int getCapacity(){
return data.length-1;
}
@Override
public int getSize(){
return size;
}
@Override
public boolean isEmpty(){
return front==tail;
}
@Override
public void enqueue(E e){
if ((tail+1)%data.length==front)
resize(getCapacity()*2);
data[tail]=e;
tail=(tail + 1) % data.length;
size++;
}
@Override
public E dequeue(){
if(isEmpty())
throw new IllegalArgumentException("Cannot dequeue from an empty queue.");
E ret =data[front];
data[front]=null;
front=(front+1)%data.length;
size--;
if (size==getCapacity()/4&&getCapacity()/2!=0)
resize(getCapacity()/2);
return ret;
}
@Override
public E getFront(){
if(isEmpty())
throw new IllegalArgumentException("Queue is empty.");
return data[front];
}
private void resize(int newCapacity) {
E [] newData= (E[]) new Object[newCapacity+1];
for (int i=0;i<size;i++){
newData[i]=data[(i+front)%data.length];
}
data=newData;
front=0;
tail=size;
}
@Override
public String toString(){
StringBuilder res = new StringBuilder();
res.append(String.format("queue: size = %d , capacity = %d\n", size, getCapacity()));
res.append(" front [");
for(int i = front ; i !=tail ; i=(i+1)%data.length){
res.append(data[i]);
if((i + 1) % data.length != tail)
res.append(", ");
}
res.append("] tail");
return res.toString();
}
}