基于数组实现的java顺序队列

public class ArrayQueen {
    // 数组:items
    private String[] items;
    //数组大小n
    private int n = 0;
    // head表示队头下标,tail表示队尾下标
    private int head = 0;
    private int tail = 0;

    // 申请一个大小为capacity的数组
    public ArrayQueen(int capacity) {
        items = new String[capacity];
        n = capacity;
    }

    // 入队-- O(n)
//    public boolean enqueue(String item) {
//        // 如果tail == n 表示队列已经满了
//        if (tail == n) return false;
//        items[tail] = item;
//        ++tail;
//        return true;
//    }


    // 入队操作,将item放入队尾
    public boolean enqueue(String item) {
        // tail == n表示队列末尾没有空间了
        if (tail == n) {
            // tail ==n && head==0,表示整个队列都占满了
            if (head == 0) return false;
            // 数据搬移 -->迁移 腾出head之前的空间
            for (int i = head; i < tail; ++i) {
                items[i-head] = items[i];
            }
            // 搬移完之后重新更新head和tail
            tail =tail-head;
            head = 0;
        }

        items[tail] = item;
        ++tail;
        return true;
    }

    // 出队
    public String dequeue() {
        // 如果head == tail 表示队列为空
        if (head == tail) return null;
        String ret = items[head];
        //出队后往后移动1
        ++head;
        return ret;
    }

    public static void main(String[] args) {
        ArrayQueen arrayQueen = new ArrayQueen(5);
        boolean enqueue1 = arrayQueen.enqueue("1");
        boolean enqueue2 = arrayQueen.enqueue("2");
        boolean enqueue3 = arrayQueen.enqueue("3");
        boolean enqueue4 = arrayQueen.enqueue("4");
        boolean enqueue5 = arrayQueen.enqueue("5");
        boolean enqueue6 = arrayQueen.enqueue("6");
        System.out.println(enqueue1);
        System.out.println(enqueue2);
        System.out.println(enqueue3);
        System.out.println(enqueue4);
        System.out.println(enqueue5);
        System.out.println(enqueue6);
        String dequeue = arrayQueen.dequeue();
        System.out.println(dequeue);
        System.out.println("head:" + arrayQueen.head + "&tail:" + arrayQueen.tail);

    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

焱童鞋

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

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

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

打赏作者

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

抵扣说明:

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

余额充值