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

a) 构建IntStack类,用int数组来存储栈内元素,用int来表示top和bottom。在IntStack类内,实现栈的基本运算,包括:
i. 栈的初始化;
ii. 判断栈是否满为空;
iii. 进栈操作(push);
iv. 退栈操作(pop);
v. 读取栈顶元素;
vi. 求栈的长度等。
b) 编写主类,测试IntStack类。包括:构建IntStack对象,并测试每一个方法,将测试结果输出到屏幕上。

第1个回答  2015-12-25
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);
}
}
}本回答被网友采纳
第2个回答  2012-03-18
我没看出来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; }
}本回答被提问者采纳
相似回答