左神视频day03——题目一:用数组结构实现大小固定的栈和队列

用数组结构实现大小固定的栈和队列

在这里插入图片描述
在这里插入图片描述

public class Array_To_Stack_Queue {

    public static class ArrayStack {
        private Integer[] arr;
        private Integer index; //构建一个指针index,数组中没有数时指向0,在数组的0位置添加一个数后index指向1

        public ArrayStack(int initSize) {
            if (initSize < 0) {
                throw new IllegalArgumentException("The init size is less than 0");
            }
            arr = new Integer[initSize];
            index = 0;
        }

        public Integer peek() { //返回栈顶元素但不移除它
            if (index == 0) {
                return null;
            }
            return arr[index - 1]; //index往下一位指向的才是栈顶
        }

        public void push(int obj) { //添加操作
            if (index == arr.length) {
                throw new ArrayIndexOutOfBoundsException("The queue is full");
            }
            arr[index++] = obj;
        }

        public Integer pop() { //弹出操作
            if (index == 0) {
                throw new ArrayIndexOutOfBoundsException("The queue is empty");
            }
            //在数组0位置添加一个数后index指向1,执行弹出操作时需要index往下移一位指向0位置的数,表示弹出了,后续添加操作加入的数会直接覆盖此时0位置的数。
            return arr[--index];
        }
    }

    public static class ArrayQueue {
        private Integer[] arr;
        private Integer size;
        private Integer start;
        private Integer end;

        public ArrayQueue(int initSize) {
            if (initSize < 0) {
                throw new IllegalArgumentException("The init size is less than 0");
            }
            arr = new Integer[initSize];
            size = 0;
            start = 0;
            end = 0;
        }

        public Integer peek() { //返回队顶元素但不移除它
            if (size == 0) {
                return null;
            }
            return arr[start];
        }

        public void push(int obj) { //添加操作,size加1,end加1
            if (size == arr.length) {
                throw new ArrayIndexOutOfBoundsException("The queue is full");
            }
            size++;
            arr[end] = obj;
            end = end == arr.length - 1 ? 0 : end + 1; //如果end已经指向末尾,由于进行添加操作后end需要加1,所以把end移到数组开头
        }

        public Integer poll() { //弹出操作,size减1,start加1
            if (size == 0) {
                throw new ArrayIndexOutOfBoundsException("The queue is empty");
            }
            size--;
            int tmp = start;
            start = start == arr.length - 1 ? 0 : start + 1; //如果start已经指向数组末尾,由于进行弹出操作后start需要加1,所以把start移到数组开头
            return arr[tmp];
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值