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

数组实现队列

设置3个变量,size记录队列长度,first记录头指针,last记录尾部的下一个节点。

代码如下:

public static class ArrayQueue {
        private Integer[] arr;
        private Integer size;
        private Integer first;
        private Integer last;

        private ArrayQueue(int initSize) {
            if (initSize == 0) {
                throw new IllegalArgumentException("this init size is less than 0");
            }
            arr = new Integer[initSize];
            size = 0;
            first = 0;
            last = 0;
        }

        public int peek() {
            if (size==0) {
                return null;
            }
            return arr[first];
        }

        public void push(int a) {
            if (size == arr.length) {
                throw new ArrayIndexOutOfBoundsException("index out of bounds");
            }
            size++;
            arr[last] = a;
            last = last==arr.length-1 ? 0:last+1;
        }

        public int poll() {
            if (size==0) {
                throw new ArrayIndexOutOfBoundsException("empty");
            }
            size--;
            int temp = first;
            first = first==arr.length-1 ? 0:first+1;
            return arr[temp];
        }
    }

数组实现栈

public static class ArrayStack {
        private Integer size;
        private Integer[] arr;
         public static int peek() {
             if (size == 0){
                 throw new ArrayIndexOutOfBoundsException("EMPTY");
             }
             return arr[size-1];
         }

         public static void push(int a) {
             if (size == arr.length) {
                 throw new ArrayIndexOutOfBoundsException("full");
             }
             arr[size++] = a;
         }

         public static int pop() {
             if (size == 0) {
                 throw new ArrayIndexOutOfBoundsException("empty");
             }
             return arr[--size];
         }
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值