循环队列的实现(Java)

循环对列判空的条件:head==tail

判断对列满的条件: (tail+1)%n==head

注意对列的tail 指针指向队尾,这个位置不存数据,为了区别队列空,和队列满的条件


/**
 * 基于数组实现的循环队列
 */
public class ArrayQueue {
    private String item[];//字符串数组实现队列
    private int n = 0;//对列元素个数
    private int head = 0;//对头元素下标
    private int tail = 0;//队尾元素下标

    //初始化
    public ArrayQueue() {
    }

    public ArrayQueue(int capacity) {
        this.item = new String[capacity];//申请一个固定大小capacity 的字符串数组空间
        this.n = capacity;
    }
    //入队
    public boolean enQueue(String item) {
        if ((tail + 1) % n == head) return false;
        this.item[tail] = item;
        //尾指针后移
        tail = (tail + 1) % n;
        return true;
    }
    //出队
    public String deQueue() {
        if (head == tail) return null;
        String he = item[head];
        head = (head + 1) % n;
        return he;
    }
}

我这里给出测试:


public class ArrayQueueTest {
    @Test
    public void test(){
        ArrayQueue aq=new ArrayQueue(4);
        aq.enQueue("1");
        aq.enQueue("2");
        aq.enQueue("3");
        aq.enQueue("5");
        System.out.println(aq.deQueue());
        System.out.println(aq.deQueue());
        System.out.println(aq.deQueue());
        System.out.println(aq.deQueue());
    }

 这里我给出队列的长度为4,表示只能存  3  个数据,再继续存的话就存不进去了,只能,出队后再继续存,才能存进去。

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

朝闻道 ||

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值