用一维整数数组实现数据结构中的堆栈(Stack)。(用java语言)
发布网友
发布时间:2022-04-27 08:09
我来回答
共2个回答
热心网友
时间:2022-06-28 22:14
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);
}
}
}
热心网友
时间:2022-06-28 22:15
我没看出来bottom有任何作用...
public class Test{
public static void main(String[] args){
IntStack stack = new IntStack(2);
System.out.println(stack.isEmpty());
stack.push(1);
System.out.println(stack.peek());
stack.push(2);
System.out.println(stack.isFull());
System.out.println(stack.pop());
System.out.println(stack.size());
}
}
class IntStack {
private int[] stack;
private int top = 0;
IntStack(int n) {
stack = new int[n];
}
boolean isEmpty() { return top == 0; }
boolean isFull() { return top == stack.length; }
boolean push(int d) { return isFull() ? false : (stack[top++] = d) == d; }
int pop() {
if (isEmpty()) throw new java.util.NoSuchElementException();
return stack[--top];
}
int peek() {
if (isEmpty()) throw new java.util.NoSuchElementException();
return stack[top - 1];
}
int size() { return top; }
}