【數據結構】隊列之順序隊列

public class SequenceQueue<T> {

    private int DEFAULT_SIZE = 10;
    // 保存數組的長度
    private int capacity;
    // 定義一個數組用於保存順序隊列的元素
    private Object[] elementData;
    // 保存順序隊列中元素的當前個數
    private int front = 0;
    private int rear  = 0;
    // 以默認數組長度建立空順序隊列
    public SequenceQueue() {
        capacity = DEFAULT_SIZE;
        elementData = new Object[capacity];
    }
    // 以一個初始化元素來建立順序隊列
    public SequenceQueue(T element) {
        this();
        elementData[0] = element;
        rear++;
    }
    /**
     * 以指定長度的數組來建立順序隊列
     * @param element 指定順序隊列中第一個元素
     * @param initSize 指定順序隊列底層數組的長度
     */
    public SequenceQueue(T element, int initSize) {
        this.capacity = initSize;
        elementData = new Object[capacity];
        elementData[0] = element;
        rear++;
    }
    // 獲取順序隊列的大小
    public int length() {
        return rear -front;
    }
    // 判斷順序隊列是否爲空隊列
    public boolean empty() {
        return rear == front;
    }
    // 插入隊列
    public void add(T element) {
        if (rear > capacity - 1) {
            throw new IndexOutOfBoundsException("隊列已滿的異常");
        }
        elementData[rear++] = element;
    }
    // 移除隊列
    public T remove() {
        if (empty()) {
            throw new IndexOutOfBoundsException("空隊列異常");
        }
        // 保留隊列的rear端的元素的值
        T oldValue = (T)elementData[front];
        // 釋放隊列的rear端的元素
        elementData[front++] = null;
        return oldValue;
    }
    // 返回隊列頂元素,但不刪除隊列頂元素
    public T element() {
        if (empty()) {
            throw new IndexOutOfBoundsException("空隊列異常");
        }
        return (T)elementData[front];
    }
    // 清空順序隊列
    public void clear() {
        Arrays.fill(elementData, null);
        front = 0;
        rear  = 0;
    }
    public String toString() {
        if (empty()) {
            return "[]";
        } else {
            StringBuilder sb = new StringBuilder("[");
            for (int i = front; i < rear; i++) {
                sb.append(elementData[i].toString() + ", ");
            }
            int len = sb.length();
            return sb.delete(len - 2, len).append("]").toString();
        }
    }
}
public class SequenceQueueTest {
    public static void main(String[] args) {
        SequenceQueue<String> queue = new SequenceQueue<String>();
        queue.add("aaaa");
        queue.add("bbbb");
        queue.add("cccc");
        queue.add("dddd");
        System.out.println("順序隊列初始化元素:" + queue.toString());
        System.out.println("訪問順序隊列的front端元素:" + queue.element());
        System.out.println("移除順序隊列的front端元素:" + queue.remove());
        System.out.println("第一次移除front端元素後:" + queue.toString());
        System.out.println("移除順序隊列的front端元素:" + queue.remove());
        System.out.println("第二次移除front端元素後:" + queue.toString());
    }
}
相關文章
相關標籤/搜索