循环队列

转载请注明出处

循环队列

循环队列主要注意两点:

  1. 处理队头与队尾指针的循环移动
    front = (front+1)%queueSize
    rear = (rear+1)%queueSize
  2. 判断何时队列为空,何时为满
    front == rear 时,可能为空,也可能为满,所以要用(rear+1)%queueSize == front 来区分队列为满(当然也可以用(front +1)%queueSize == rear 来区分队列为空)

相关图示
循环队列

代码实现
CycleQueue 实现类(实际实现中要面向接口编程)

public class CycleQueue {

    private Object[] objects;
    private int queueSize;
    private int front;
    private int rear;

    public CycleQueue(int queueSize) {
        this.queueSize = queueSize;
        objects = new Object[queueSize];
    }

    public boolean push(Object object) {
        int tempRear = (rear+1)%queueSize;
        if (tempRear == front) {
            System.out.println("队列满了");
            return false;
        }else {
            objects[rear] = object;
            rear = tempRear;
            return true;
        }
    }

    public Object pop() {
        if (front == rear) {
            System.out.println("队列已为空");
            return null;
        }else {
            Object object = objects[front];
            front = (front+1)%queueSize;
            return object;
        }

    }

}

测试类

public class CycleQueueTest {
    public static void main(String[] args) {
        CycleQueue cycleQueue = new CycleQueue(5);
        cycleQueue.pop();
        cycleQueue.push(4);
        cycleQueue.push("fds");
        int a = (int) cycleQueue.pop();
        String str = (String) cycleQueue.pop();
        System.out.println(a + " " + str);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值