美文网首页
大话数据结构—循环队列(七)

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

作者: 浅浅星空 | 来源:发表于2019-02-20 10:35 被阅读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;
        }
    }
    

    相关文章

      网友评论

          本文标题:大话数据结构—循环队列(七)

          本文链接:https://www.haomeiwen.com/subject/mwycyqtx.html