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

本文详细介绍如何使用数组实现队列和栈这两种基本的数据结构。通过设置头指针、尾指针和队列长度,实现了队列的push、poll和peek操作;并通过数组和大小变量实现了栈的push、pop和peek操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

数组实现队列

设置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];
         }
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值