1. 程式人生 > >Java實現環形佇列(入隊、出隊)

Java實現環形佇列(入隊、出隊)

public class Class_queue {

    private int q_head;
    private int q_tail;
    private int[] queue;
    private int len;
    private int length;

    public Class_queue(int length) {
        super();
        this.length = length;
        q_head = 0;
        q_tail = 0;
        queue = new int[length];
    }

    public boolean isFull() {
        if (len == length) {
            return true;
        }
        return false;
    }

    public boolean isEmpty() {
        if (len == 0) {
            return true;
        }
        return false;
    }

    public void Enqueue(int x) {
        if (!isFull()) {
            queue[q_tail] = x;
            q_tail = (q_tail + 1) % length;
            len++;
        } else {
            System.out.println("佇列已滿");
        }
    }

    public int Dequeue() {
        int ele = -1;
        if (!isEmpty()) {
            ele = queue[q_head];
            q_head = (q_head + 1) % length;
            len--;
        }
        return ele;
    }

    public void Queue_print() {
        if (q_tail > q_head) {
            for (int i = q_head; i < q_tail; i++) {
                System.out.println(queue[i]);
            }
        }
        if (q_tail <= q_head) {
            for (int i = q_head; i < length; i++) {
                System.out.println(queue[i]);
            }
            for (int i = 0; i < q_tail; i++) {
                System.out.println(queue[i]);
            }
        }
    }

}