數(shù)據(jù)結(jié)構(gòu)--隊列--范例
“ 每天都可以成長一點點”
01
—
public class ArrayQueue {
//隊列容量
public int size;
//隊列頭部下標
public int front;
//隊列尾部下標
public int rear;
//數(shù)組
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];
}
}
評論
圖片
表情
