【发布时间】:2017-08-12 09:33:13
【问题描述】:
您好,我正在尝试使用另一个空堆栈来反转堆栈(我自己编写的堆栈)。由于某种原因,它无法正常工作。谁能帮我这个 ?
public static void main(String[] args) {
Stack stack1 = new Stack();
//filling the stack with numbers from 0 to 4
for(int i = 0; i < Constants.MAX_ELMNTS; i++){
stack1.push(new Integer(i));
System.out.println(i);
}
Stack reverse = new Stack();
while(stack1.getNbElements() > 0){
reverse.push(stack1.pop());
}
【问题讨论】:
-
请定义“不能正常工作”。您还可以在第一个循环中填充变量
stack并在第二个循环中使用变量stack1。 -
您向我们展示了用于测试您的课程的代码。你真正应该向我们展示的是 push 和 pop 的代码(也许还有 getNbElements())
-
由于是自定义栈,需要实际实现后才建议reverse()的最优策略。
-
更新我 99% 确定它正在工作,但我不知道如何输出反向。它输出:“stack@1540e19d”。这是什么?
-
@DoctorLongLegs 我已更新答案以包含值的输出。