java学习笔记 基础 数组模仿栈的操作

本文介绍了一个使用数组实现的栈的数据结构,并提供了相应的MyStack类实现代码。该类包括了初始化、压栈、出栈、获取栈顶元素及删除指定数量元素的功能。通过异常处理确保操作的安全性。

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

学习junit想写一个栈的测试类练习,于是用数组实现了栈

package com.zhumin.junit;

/**
 * Created by charleszhu on 14-2-8.
 */
public class MyStack{

    private int[] stack;

    // 下一个元素编号
    private int nextIndex;

    public MyStack(){

        stack = new int[100];

    }

    /**
     * 初始化
     */
    public void init(){

        nextIndex =0;

    }

    /**
     * 如栈
     * @param element
     * @throws Exception
     */
    public void push(int element) throws Exception{

        if(100==nextIndex){
            throw new Exception("数组越界错误");
        }

        stack[nextIndex++] = element;
    }

    /**
     * 弹出
     * @throws Exception
     */
    public int pop() throws Exception{

        if(0==nextIndex){
            throw new Exception("数组越界错误");
        }

        return stack[--nextIndex];
    }

    /**
     * 获得栈定元素
     * @return 栈定元素
     * @throws Exception
     */
    public int top() throws Exception{

        if(0==nextIndex){

            throw new Exception("数组越界错误");
        }

        return stack[nextIndex-1];
    }

    /**
     * 删除栈中length个元素
     * @param length
     * @throws Exception
     */
    public void delete(int length) throws Exception{

        if(nextIndex-length<0){

            throw new Exception("素组越界错误");
        }

        nextIndex -=length;
    }

}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值