数组实现固定大小的堆和栈

数组实现栈:栈是一种后进先出的数据结构,用数组实现起来比较简单。

package lianxi03;

public class Code01_Array_Stcak {
    public static void main(String[] args) {
        ArrayStack s=new ArrayStack(2);
        s.add(1);
        s.add(2);
        System.out.println(s.peek());

    }
    public static class ArrayStack{
        private Integer[] arr;
        private Integer size;
        public ArrayStack(int initSize){
            if(initSize<0)throw new IllegalArgumentException("The inti size is less than 0");
            arr=new Integer[initSize];
            size=0;
        }
        public  void add(int num){
            if(size>=arr.length)
                throw new ArrayIndexOutOfBoundsException("The array is full");
            arr[size++]=num;
        }
        public Integer pop(){
            if(size==0)throw new ArrayIndexOutOfBoundsException("The array is empty");
            return arr[--size];
        }
        public Integer peek(){
            if(size==0)return null;
            return arr[size-1];
        }


    }
}

数组实现堆:堆是一种先进先出的数据结构,用数组实现堆的过程中,除了要用一个size来记录数组的大小,还需要一个first来记录数组的开始位置,以及last来确定数组的末尾位置。

package lianxi03;

import java.lang.reflect.Array;

public class Code02_Array_Queue {
    public static void main(String[] args) {
        Array_Queue queue=new Array_Queue(3);
        queue.add(1);
        queue.add(2);
        System.out.println(queue.peek());
        System.out.println(queue.pop());
        System.out.println(queue.pop());

    }
    public static class Array_Queue{
        private Integer[] arr;
        private Integer size;
        private Integer first;
        private Integer last;
        public Array_Queue(int intiSize){
            if(intiSize<0)throw new IllegalArgumentException("The inti is less than 0");
            arr=new Integer[intiSize];
            size=0;
            first=0;
            last=0;
        }
        public void add(int num){
            if(size==arr.length)throw new ArrayIndexOutOfBoundsException("The array is full");
            size++;
            arr[last]=num;
            last=last==arr.length-1?0:last+1;
        }
        public Integer peek(){
            if(size==0)return null;
            return arr[first];
        }
        public Integer pop(){
            if(size==0)throw new ArrayIndexOutOfBoundsException("The array is empty");
            size--;
            int tmp=arr[first];
            first=first==arr.length-1?0:first+1;
            return tmp;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值