队列的顺序存储实现
基本概念队是一种线性结构,是一种只允许在表的一端进行插入操作,而另外一端进行删除的线性表。
- 允许插入的一端称之为“队尾”:插入又称之为入队
- 允许删除的一端称之为“队头”:删除又称之为出队
public class QueueList {
public int size;
public int front;
public int rear;
public int[] queue;
public QueueList(int size) {
this.size = size;
this.front= -1;
this.rear = -1;
this.queue= new int[this.size];
}
public boolean isEmpty() {
return this.front==this.rear;
}
public boolean isFull() {
return this.rear+1==this.size;
}
public Integer getFrontEle() {
if(isEmpty())return -1;
return this.queue[this.front+1];
}
public Integer getRearEle() {
if(isEmpty())return -1;
return this.queue[this.rear];
}
public boolean InQueue(int value) {
if(isEmpty())return false;
this.queue[++this.rear]=value;
return true;
}
public Integer OutQueue() {
if(isEmpty())return -1;
return this.queue[++this.front];
}
}
存在的问题:
* 这里存在的一个很大的问题是:
* 数组中,队头指针front走过的位置不会再被使用,这就造成的存储上的浪费
* 相应的提出了循环队列的实现。
* 值得一提的是,对列的链式存储不会考虑存储浪费问题,
* 因为,结点占用的空间在动态的创建和释放过程中。
public class CycleQueueList {
public static void main(String[] args) {
CycleQueueList queu = new CycleQueueList(3);
System.out.println(queu.InQueue(1));
System.out.println(queu.InQueue(2));
System.out.println(queu.InQueue(3));
System.out.println(queu.InQueue(4));
System.out.println(queu.getRearEle());
System.out.println(queu.isFull());
System.out.println(queu.OutQueue());
System.out.println(queu.InQueue(4));
System.out.println(queu.getRearEle());
}
public int size;
public int front;
public int rear;
public int[] queue;
public CycleQueueList(int size) {
this.size = size+1;// +1的目的在于,front指向了头元素的前一个结点,因而浪费了一个存储空间,因此+1补充
this.front= 0;
this.rear = 0;
this.queue= new int[this.size];
}
public boolean isEmpty() {
return this.front == this.rear;
}
public boolean isFull() {
return (this.rear+1)%this.size == this.front;
}
public Integer getFrontEle() {
if(isEmpty())return -1;
return this.queue[(this.front+1)%this.size];
}
public Integer getRearEle() {
if(isEmpty())return -1;
return this.queue[this.rear];
}
public boolean InQueue(int val) {
if(isFull())return false;
this.rear = (this.rear+1)%this.size;
this.queue[this.rear]=val;
return true;
}
public boolean OutQueue() {
if(isEmpty())return false;
this.front = (this.front+1)%this.size;
return true;
}
}



