private int[] stack
private int top
/**
*初始化栈,传入一个非负的整数,否则抛出一个错误
*/
public IntStack(int size) throws StackErrorException{
if(size<0){
throw new StackErrorException("错误的大小")
}
init(size)
}
private void init(int size) {
stack = new int[size]
top = 0
}
/**
*判断栈是否为空,true则为空,反之则反
*/
public boolean isEmpty(){
return top==0
}
/**
*判断栈是否已满,true则已满,反之则反
*/
public boolean isFull(){
return top==stack.length
}
/**
*/
public void push(int value) throws StackErrorException{
if(isFull()){
throw new StackErrorException("栈已满")
}
stack[top++] = value
}
/**
*移除栈顶元素并返回,空则抛出异常
*/
public int pop() throws StackErrorException{
if(isEmpty()){
throw new StackErrorException("已到栈底!")
}
return stack[--top]
}
/**
*返回栈顶元素,空则抛出异常
*/
public int peek() throws StackErrorException{
if(isEmpty()){
throw new StackErrorException("已在栈底!")
}
return stack[top-1]
}
/**
*返回栈大小
*/
public int size(){
return stack.length
}
class StackErrorException extends Exception{
public StackErrorException(String msg) {
super(msg)
}
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)