大话数据结构—循环队列(七)

2019-02-20  本文已影响3人  浅浅星空

1.循环队列

a.队列满的条件是 (rear+l) % QueueSlze==front
b.通用的计算队列长度公式为:(rear- front + QueueSize) %QueueSize

public class CircleQueue {

    private static final int MAX_SIZE = 10;
    private Object[] data = new Object[MAX_SIZE];
    private int front;
    private int rear;

    public CircleQueue() {
        front = rear = 0;
    }

    public int size() {
        return (MAX_SIZE - front + rear) % MAX_SIZE;
    }

    public void add(Object element) {
        if ((rear + 1) % MAX_SIZE == front) {
            throw new RuntimeException("队列满");
        }
        data[rear] = element;
        rear = (rear + 1) % MAX_SIZE;
    }

    public Object poll() {
        if (front == rear) {
            throw new RuntimeException("空队列");
        }
        Object element = data[front];
        front = (front + 1) % MAX_SIZE;
        return element;
    }
}
上一篇下一篇

猜你喜欢

热点阅读