【编程题】用数组实现栈(Java实现)

【编程题】用数组实现栈(Java实现)

题目描述

通过一个数组实现栈的功能,具有出栈、压栈、计算当前栈的元素值、以及栈的大小等方法。
思路
在数组中用一个index指向当前元素的位置,压栈就往上添加,出栈就往下减少,元素个数即当前位置到开始位置个数,栈的大小为数组的大小。
代码

package niuke;

public class ArrayStack {
    public static void main(String[] args){
        ArrayStack stack=new ArrayStack(3);
        stack.push(1);
        stack.push(3);
        stack.push(4);
        System.out.println(stack.peek());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        // System.out.println(queue.pop());
    }
   private Integer arr[];
   private Integer index;
   public  ArrayStack(int initSize){
       if(initSize<0){
           throw new IllegalArgumentException("initSize must more than 0");
       }
       arr=new Integer[initSize];
       index=0;
   }
   public Integer peek(){
       if(index==0)
           return null;
       return arr[index-1];
   }
   public void push(int val){
       if(index==arr.length){
           throw new ArrayIndexOutOfBoundsException("The stack is full");
       }
      arr[index++]=val;
   }
   public Integer pop(){
       if(index==0){
           throw new ArrayIndexOutOfBoundsException("The stack is empty");
       }
       return arr[--index];
   }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值