基于数组实现: 栈 队列

 * 栈和队列实现:
 *      1.双向链表实现
 *      2.数组实现
 *
 * 基于数组实现

public class StackOrQueueBaseOnArray {

    /**
     * 数组实现栈:
     *      1.只要满了报异常
     *      2.没满保证正确性
     */
    public static class ArrayStack{
        private int index;
        private final int[] arr;
        private static final int INIT_CAPACITY = 10;

        public ArrayStack(){
            this(INIT_CAPACITY);
        }

        public ArrayStack(int capacity){
            this.arr = new int[capacity];
        }

        public void push(int val){
            if(index == arr.length){
                System.out.println("this stack is full!");
                return;
            }
            this.arr[index] = val;
            this.index ++;
        }

        public int pop(){
            if(index <= 0){
                return -1;
            }
            index --;
            return this.arr[index];
        }
    }

    /**
     * 数组实现队列:
     *      1.可循循环利用现有的数组容量
     *      2.确定一种机制实现循环可用的队列,类似: ring buffer
     */
    public static class ArrayQueue{
        private final int[] arr;
        /*记录存入元素的下一个位置*/
        private int pushIndex;
        /*记录刚被取出的元素位置*/
        private int popIndex;
        /*有效数据容量*/
        private int size;
        private final int limit;

        public ArrayQueue(int limit) {
            this.arr = new int[limit];
            this.pushIndex = 0;
            this.popIndex = 0;
            this.size = 0;
            this.limit = limit;
        }

        public void push(int val){
            if(size == limit){
                throw new RuntimeException("队列已满");
            }
            size ++;
            arr[pushIndex] = val;
            pushIndex = nextIndex(pushIndex);
        }

        public int pop(){
            if(isEmpty()){
                throw new RuntimeException("队列已空");
            }
            size --;
            int res = arr[popIndex];
            popIndex = nextIndex(popIndex);
            return res;
        }

        public boolean isEmpty(){
            return size == 0;
        }

        public boolean isFull(){
            return size == limit;
        }
        /*index传入时已经读写了数据,只是改变下一次的索引*/
        private int nextIndex(int index){
            return index < limit - 1 ? index + 1 : 0;
        }
    }
}

左神算法学习

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值