java模拟实现栈(Stack)

简单模拟实现栈(Stack)结构,出栈(pop),入栈(push),查看栈顶元素(peek)....

import java.util.Arrays;


public class MyStack {
    int[] elementData;
    int usedSize;

    //构造方法
    public MyStack() {
        this.elementData = new int[5];
        this.usedSize = 0;//既代表有效长度,又代表当前位置可存放元素
    }

    //入栈
    public void push(int data) {
        //判满,扩容
        if (isFull()) {
            this.elementData = Arrays.copyOf(this.elementData , 2*this.elementData.length);
        }
        this.elementData[usedSize] = data;
        this.usedSize++;//长度加1
    }

    //出栈
    public int pop() {
        //栈空
        if(empty()){
            throw new RuntimeException("栈空,无法出栈");//应该自己写个异常类
        }
        this.usedSize--;
        int ret = elementData[usedSize];
        //elementData[usedSize] = null;如果是引用类型的话
        return ret;
    }

    //获取顶部元素
    public int peek() {
        //栈空
        if(empty()){
            throw new RuntimeException("栈空,无法查看栈顶元素");
        }
        return this.elementData[this.usedSize - 1];
    }

    //判空
    public boolean empty() {
        if (this.usedSize == 0)
            return true;
        return false;
    }
    //判空2
    public boolean empty2(){
        return this.usedSize == 0;
    }

    //计算长度
    public int size() {
        return this.usedSize;
    }

    //判满
    public boolean isFull(){
        if(this.usedSize == this.elementData.length)
            return true;
        return false;
    }
    //判满2
    public boolean isFull2(){
        return this.usedSize == this.elementData.length;
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值