1. 程式人生 > >Java迴圈佇列簡單實現

Java迴圈佇列簡單實現

public class Queue {

    private int MAX_CAPACITY;
    private int[] data;
    private int front;
    private int rear;
    private int nItems;

    public Queue(int capacity){
        if(capacity < 0)
            throw new IllegalArgumentException("Illegal capacity: " + capacity);
        MAX_CAPACITY = capacity;
        data = new
int[MAX_CAPACITY]; front = 0; rear = -1; nItems = 0; } public Queue(){ this(10); } public void insert(int value){ if(isFull()) throw new FullQueueException("queue is full"); if(rear == MAX_CAPACITY-1) // 因為是陣列實現,所以陣列頂端應該是MAX_CAPACITY-1
rear = -1; // 為什麼初始狀態是-1,因為陣列下標從0開始 data[++rear] = value; nItems++; } public int remove(){ if(isEmpty()) throw new EmptyQueueException("queue is empty"); int temp = data[front++]; if(front == MAX_CAPACITY) front = 0
; // 陣列下標從0開始,front=0可以直接取 nItems--; // 多維護一個佇列大小變數,可以讓isFull()、isEmpty()函式變得很簡潔 return temp; } public int peek(){ if(isEmpty()) throw new EmptyQueueException("queue is empty"); return data[front]; } public boolean isFull(){ return (nItems == MAX_CAPACITY); } public boolean isEmpty(){ return (nItems == 0); } public int size(){ return nItems; } public static void main(String[] args) { Random random = new Random(); Queue queue = new Queue(); int CAPACITY = 10; System.out.println("----入列-----"); for(int i=0;i<CAPACITY;i++){ queue.insert(random.nextInt(100)); } System.out.println("元素數量:" + queue.size()); System.out.println("----出列-----"); for(int i=0;i<CAPACITY;i++){ System.out.println(queue.remove()); } } }

注意幾點:
1、解決”假溢位”問題:迴圈佇列
2、擔心rear一直迴圈會覆蓋原來的值?:在insert之前加入isFull()判斷,如果佇列滿(front==rear),則不會繼續插入
3、擔心front一直迴圈會取不到值?:在remove之前加入isEmpty()判斷,如果佇列為空(front==rear),則不會繼續取值
4、front和rear一直互相追著跑
5、ADT中多維護一個變數(標識當前佇列中元素數量),會讓isFull()、isEmpty()程式碼簡潔很多
6、異常處理原理同堆疊