【发布时间】:2013-12-18 12:10:14
【问题描述】:
我需要帮助的事情是:
使 isEmpty() 和 isFull() 方法返回答案以告诉我堆栈是否为空或堆栈是否已满的正确代码是什么
我需要将我正在使用的堆栈设置为五 (5) 个(堆栈可以容纳 5 个整数)
我需要在 push() 和 pop() 方法中添加异常,当堆栈已满时不允许使用 push,或者在堆栈为空时使用 pop
import java.util.ArrayList;
import java.util.List;
public class IntegerStack {
private List<Integer> stack;
public IntegerStack(int SIZE) {
stack = new ArrayList<Integer>(SIZE);
}
/* method to push the stack */
public void push(int i) {
stack.add(0, i);
}
/* method to pop the stack */
public int pop() {
if (!stack.isEmpty()) {
int i = stack.get(0);
stack.remove(0);
return i;
} else {
return -1;// Or any invalid value
}
}
/* method to peek at the stack */
public int peek() {
if (!stack.isEmpty()) {
return stack.get(0);
} else {
return -1;// Or any invalid value
}
}
/* determine if the stack is empty */
public boolean isEmpty() {
stack.isEmpty();
}
/* determine if the stack is full */
public boolean isFull() {
stack.isFull();
}
/* determine the size of the stack */
public int size() {
if (stack.isEmpty())
return 0;
else
return stack.size();
}
}
【问题讨论】:
-
你应该正确缩进你的代码,它真的很难阅读它
-
一开始你错过了return关键字。返回堆栈.isEmpty();返回 stack.isFull();
-
如果这是一个Stack,为什么推的时候还要提供一个位置?
-
您也可以咨询
the java.util.Stack类获取更多帮助。