1. 程式人生 > >陣列模擬佇列

陣列模擬佇列

 

 

 

 

/**
 * 使用陣列模擬佇列
 * @author Administrator
 */

public class ArrayQueueDemo {
    public static void main(String[] args) {
        ArrayQueue arrayQueue = new ArrayQueue(3);
        arrayQueue.addQueue(2);
        arrayQueue.addQueue(4);
        arrayQueue.addQueue(6);
        arrayQueue.showQueue();
    }
    
}

//使用陣列模擬一個有序佇列
class ArrayQueue{
    private int front = -1;//佇列頭
    private int rear = -1;//佇列尾
    private int maxSize;//表示陣列的最大容量
    private int[] arr ;//該陣列用於存放資料,模擬佇列
    
    //建構函式初始化佇列
    public ArrayQueue(int maxSize){
        this.maxSize = maxSize;
        arr = new int[maxSize];
    }
    
    //判斷是否滿了
    public boolean fullQueue(){
        return rear == maxSize-1;
    }
    
    //判斷是否為空
    public boolean isEmpty(){
        return rear == front;
    }
    
//新增元素
    public void addQueue(int n){
        //校驗是否滿了
        if (fullQueue()) {
            System.out.println("佇列已經滿了");
            return;
        }
        //新增到佇列中
        rear++;
        arr[rear] = n;
    }
    
    //去除元素
    public int removeQueue(){
        //校驗是否為空
        if (isEmpty()) {
            throw new RuntimeException("當前為空不能去除元素!");
        }
        front++;
        return arr[front]; 
    }
    
    public void showQueue(){
        if (!isEmpty()) {
            for (int i = 0; i < arr.length; i++) {
                System.err.println(arr[i]);
            }
        }
        
    }
    
     
}

&n