假设front指向队列的头部,rear指向队列的尾部。
- 则队列满的条件是:(rear+1)%QueueSize==front
- 则队列为空的条件为:rear==front
- 通用的计算队列长度的公式:(rear-front+QueueSize)%QueueSize
则队列的数组实现如下:
private int[] array;
private int front;
private int rear;
public MyQueue(int capacity){
this.array=new int[capacity];
}
/**
*入队
*/
public void enQueue(int element)throws Exception{
if((rear+1)%array.length==front){
throw new Exception("队列已满");
}
array[rear]=element;
rear=(rear+1)%array.length;
}
/**
*出队
*/
public int deQueue()throws Exception{
if(rear==front){
throw new Exception("队列已空");
}
int deQueueElement=array[front];
front=(front+1)%array.length;
return deQueueElement;
}
由于链表不用像数组那样考虑容量问题,所以我们队列的链表实现就像单链表一样,只不过它只能尾进头出而已,我们把它简称为链队列。
public class LinkQueue {
/**
* 结点类
*/
class Entry{
int data;
Entry next;
public Entry(){
data=-1;
next=null;
}
public Entry(int data)
{
this.data=data;
this.next=null;
}
}
/***定义头尾索引***/
public Entry front=null;
public Entry rear=null;
public int useSize=0;
/****判断队列是否为空****/
public boolean isEmpty(){
return useSize==0;
}
/*****入队*****/
public void enQueue(int data){
//若此时队列为空,则直接插入,头尾索引指向该结点
if(isEmpty()==true){
rear=new Entry(data);
front=rear;
}
else {
//若队列不为空,则尾索引后移
rear.next=new Entry(data);
rear=rear.next;
}
useSize++;
}
/****出队*****/
public int deQueue() throws Exception{
if(isEmpty()){
throw new Exception("队列已空");
}
int deQueueElement=front.data;
front=front.next;
useSize--;
return deQueueElement;
}
/****队列遍历输出***/
public void output(){
Entry cur=front;
while (cur!=null){
System.out.println(cur.data);
cur=cur.next;
}
System.out.println();
}
public static void main(String[] args) {
// 动态制作一个链式队列
LinkQueue link = new LinkQueue();
for (int x = 0; x < 5; x++) {
link.enQueue(x);
}
System.out.print("队列里的元素是:");
link.output();
System.out.println("队列长度是 :" + link.useSize);
System.out.println("==================");
try {
link.deQueue();
}catch (Exception e) {
System.out.println("队列为空,不能出队");
}
System.out.print("执行一次出队操作后队列里的元素是:");
link.output();
System.out.println("执行一次出队操作后队列长度是 :" + link.useSize);
}
}