java用数组实现栈

1.1.  栈的数据结构

栈是一种先进后出的数据结果,只能在一端(称为栈顶(top))对数据项进行插入和删除。

1.2.  Java实现

StackTest

package ch04;
 
public class StackTest {
 
    public static void main(String[] args) {
 
       ArrayStack stack = new ArrayStack(10);
       System.out.println("isEmpty: "+stack.isEmpty());
       for(int i = 0;i<10;i++){
           stack.push(i);
       }
       System.out.println("isFull: "+stack.isFull());
      
       while(!stack.isEmpty()){
           System.out.println(stack.pop());
       }
      
    }
 
}
 
class ArrayStack{
    private int[] arrInt;//内置数组
    private int top;//栈顶指针
   
    public ArrayStack(int size){
       this.arrInt = new int[size];
       top = -1;
    }
   
    /**
     * 判断栈是否为空
     * @return
     */
    public boolean isEmpty(){
       return -1 == top;
    }
   
    /**
     * 判断栈是否已满
     * @return
     */
    public boolean isFull(){
       return arrInt.length -1 == top;
    }
    /**
     * 向栈顶插入一个元素
     * @param item
     */
    public void push(int item){
       if(isFull()){
           throw new RuntimeException("栈已满");
       }
       arrInt[++top] = item;
    }
   
    /**
     * 从栈顶取出一个元素
     * @return
     */
    public int pop(){
       if(isEmpty()){
           throw new RuntimeException("栈为空");
       }
       return arrInt[top--];
    }
}

 

结果如下:

isEmpty: true

isFull: true

9

8

7

6

5

4

3

2

1

0

 

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

morris131

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值