学习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;
}
}