队列
队列是一种同栈Stack非常类似的结构。唯一的不同点是:最先被压入栈的数据,将会在最后被弹出栈;而队列与之相反,最先进入队列的数据会被最先从队列中取出。
这个非常好理解,比如我们在超市买东西的时候,需要排队结账。最先到达收银台的人会先结账。队列就是符合这种规律的一种数据结构:也就是我们常说的先进先出(FIFO)原则。如下图所示:
基本操作
我们已经知道,栈支持两种基本操作: 入栈(push)和出栈(pop)。队列跟栈的操作也非常相似,它支持的操作也是两个: 入队(enqueue)和出队(dequeue)。
用一张图表示如下所示:
队列的应用
队列是一种非常基础的数据结构。它的应用也非常广泛,导致它的种类可能会有很多种。我们只要在最基本的队列数据结构基础上稍加改造,就可以将其应用到很多特殊的场合。比如我们可以使用一个阻塞队列实现生产者-消费者模式、或者使用一个循环队列来实现Linux的环形缓存等等。
代码实现
class Queue
{
int front, rear, size;
int capacity;
int array[];
public Queue(int capacity) {
this.capacity = capacity;
front = this.size = 0;
rear = capacity - 1;
array = new int[this.capacity];
}
// Queue is full when size becomes equal to
// the capacity
boolean isFull(Queue queue)
{ return (queue.size == queue.capacity);
}
// Queue is empty when size is 0
boolean isEmpty(Queue queue)
{ return (queue.size == 0); }
// Method to add an item to the queue.
// It changes rear and size
void enqueue( int item)
{
if (isFull(this))
return;
this.rear = (this.rear + 1)%this.capacity;
this.array[this.rear] = item;
this.size = this.size + 1;
System.out.println(item+ " enqueued to queue");
}
// Method to remove an item from queue.
// It changes front and size
int dequeue()
{
if (isEmpty(this))
return Integer.MIN_VALUE;
int item = this.array[this.front];
this.front = (this.front + 1)%this.capacity;
this.size = this.size - 1;
return item;
}
// Method to get front of queue
int front()
{
if (isEmpty(this))
return Integer.MIN_VALUE;
return this.array[this.front];
}
// Method to get rear of queue
int rear()
{
if (isEmpty(this))
return Integer.MIN_VALUE;
return this.array[this.rear];
}
}
// Driver class
public class Test
{
public static void main(String[] args)
{
Queue queue = new Queue(1000);
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
queue.enqueue(40);
System.out.println(queue.dequeue() +
" dequeued from queue\n");
System.out.println("Front item is " +
queue.front());
System.out.println("Rear item is " +
queue.rear());
}
}
时间复杂度
同栈一样,队列的所有操作也不存在循环操作。所以队列的所有操作的复杂度都是 O(1)