1. 程式人生 > >初始資料結構——迴圈佇列(順序儲存)

初始資料結構——迴圈佇列(順序儲存)

佇列是隻允許在隊尾插入,隊頭刪除的受限制的線性表
因為普通佇列會出現假溢位現象,所以一般使用迴圈佇列

public class CircularQueue
{
	private Object[] data;
    private int head;
    private int tail;
    private int size;

   //初始化佇列
    public CircularQueue(int size) {
        data = new Object[size];
        head = -1;
        tail = -1;
        this.size = size;
    }
    
    //入隊
    public boolean enQueue(Object value) {
        if (isFull() == true) {
            return false;
        }
        if (isEmpty() == true) {
            head = 0;
        }
        tail = (tail + 1) % size;
        data[tail] = value;
        return true;
    }
    
    //出隊
    public boolean deQueue() {
        if (isEmpty() == true) {
            return false;
        }
        if (head == tail) {
            head = -1;
            tail = -1;
            return true;
        }
        head = (head + 1) % size;
        return true;
    }
    
  //取隊頭
    public Object Front() {
        if (isEmpty() == true) {
            return -1;
        }
        return data[head];
    }
    
   //取隊尾
    public Object Rear() {
        if (isEmpty() == true) {
            return -1;
        }
        return data[tail];
    }
    
   //判空
    public boolean isEmpty() {
        return head == -1;
    }
    
  //判滿
    public boolean isFull() {
        return ((tail + 1) % size) == head;
    }
}