数据结构--队列--范例
“ 每天都可以成长一点点”
01
—
public class ArrayQueue {
//队列容量
public int size;
//队列头部下标
public int front;
//队列尾部下标
public int rear;
//数组
public int arr[];
public ArrayQueue(int size){
this.size = size + 1; //默认留一个空地址
this.front = 0;
this.rear = 0;
this.arr = new int[size+1];
}
/**
* 是否满队
* @return
*/
public boolean isFull(){
return (rear+1) % size == front;
}
/**
* 是否空队
* @return
*/
public boolean isEmpty(){
return rear == front;
}
/**
* 入队
* @param item
*/
public void push(int item){
if(isFull()){
throw new RuntimeException("队列已满,入队失败");
}
arr[rear] = item;
rear = (rear + 1) % size;
}
/**
* 出队
* @return
*/
public int pop(){
if(isEmpty()){
throw new RuntimeException("队列为空");
}
int item = arr[front];
front = (front + 1) % size;
return item;
}
/**
* 队列长度
* @return
*/
public int length(){
return (rear + size - front) % size;
}
/**
* 显示整个队列
*/
public void show(){
if(isEmpty()){
throw new RuntimeException("队列为空");
}
for (int i = front; i < front+length(); i++) {
System.out.print(arr[i%size]+"\t");
}
System.out.printf("\n");
}
public int getHeader(){
if(isEmpty()){
throw new RuntimeException("队列为空");
}
return arr[front];
}
}
评论