用一维整数数组实现数据结构中的堆栈(Stack)。(用java语言)

2025-04-05 03:37:02
推荐回答(1个)
回答1:

public class IntStack {

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);
}
}
}