队列结构
队列结构是按照 “先进先出 ”(First In First Out,FIFO)的原则处理数据的。在队列结构中,允许对两端进行操作,但是在两端的操作不同。在表的一端可以进行删除操作,称为队头;在表的另一端只能进行插入操作,称为队尾。如果队列中没有数据元素,则称为空队列。
- 入队列:将一个元素添加到队尾(相当于到队列最后排队等候)。
- 出队列:将队头的元素取出,同时删除该元素,使后一个元素成为队头。
public class Queue {
private int [] queArray;
private int maxSize;
public int front;
public int tail;
private int length;
//构造方法初始化队列
public Queue(int maxSize){
this.maxSize = maxSize;
queArray = new int[maxSize];
front = 0;
tail = -1;
length = 0;
}
//判断空队列
public boolean isEmpty(){
return (length == 0);
}
//判断满队列
public boolean isFull(){
return (length == maxSize);
}
//插入
public void insert(int elem) throws Exception {
if (isFull()){
throw new Exception("队列已满,不能进行插入操作");
}else{
//如果队尾指针已达到数组的末端,插入到数组的第一个位置
if(tail == maxSize-1){
tail = -1;
}
queArray[++tail] = elem;
length++;
}
}
//移除
public int remove() throws Exception {
if (isEmpty()){
throw new Exception("队列为空,移除失败");
}
int elem = queArray[front++];
//如果队头指针已到达数组末端,则移到数组第一个位置
if(front == maxSize){
front =0;
}
length--;
return elem;
}
//查看队头元素
public int peek() throws Exception {
if (isEmpty()){
throw new Exception("队列内没有元素!");
}
return queArray[front];
}
//获取队列长度
public int size(){
return length;
}
//释放队列
public void freeQueue(){
if (queArray != null){
queArray = null;
}
}
//测试
public static void main(String[] args) throws Exception {
Queue queue = new Queue(5);
System.out.println("入队列操作:");
Scanner scanner = new Scanner(System.in);
int i;
do {
if ((i=scanner.nextInt())==0){
break;
}else{
queue.insert(i);
}
}while(true);
String temp = "1";
System.out.println(queue.isFull());
System.out.println("出队列操作:");
temp = scanner.next();
while(!temp.equals("0")){
System.out.println(queue.remove());
temp = scanner.next();
}
System.out.println("测试结束");
queue.freeQueue();
}
}