Java实现队列

来源:互联网 发布:c语言 double 误差 编辑:程序博客网 时间:2024/05/01 20:49
package test;


public class Queue {
private int maxSize;// 表示队列的大小
private int[] queArr;// 用数组来存放队列的数据
private int front;// 取数据的下标
private int rear;// 存数据的下标
private int nItems;// 记录存放数据的个数


public Queue(int s) {
maxSize = s;
queArr = new int[maxSize];
front = 0;
rear = -1;
nItems = 0;
}


public void insert(int j) {// 增加数据的方法
if (isFull()) {
return;
}
// 如果下标达到数组顶部的话,让rear指向数组的第一个位置之前
if (rear == maxSize - 1)
rear = -1;
queArr[++rear] = j;
nItems++;
}


public int remove() {
int temp = queArr[front++];
// 如果下标达到数组顶部的话,让front指向数组的第一个位置
if (front == maxSize)
front = 0;
nItems--;
return temp;
}


public int peekFront() {
// 只是返回最前面那个元素的值,并不删除
return queArr[front];
}


public boolean isEmpty() {
return (nItems == 0);
}


public boolean isFull() {
return (nItems == maxSize);
}


public int size() {
return nItems;
}


/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Queue theQueue = new Queue(4);
theQueue.insert(10);
theQueue.insert(20);
theQueue.insert(30);
theQueue.insert(40);
theQueue.remove();
theQueue.insert(50);
theQueue.insert(60);
while (!theQueue.isEmpty()) {
System.out.println(theQueue.remove());
}
}


}
0 0
原创粉丝点击