如何在java中使用另一个堆栈来反转堆栈 [英] how do I reverse a stack using another stack in java
本文介绍了如何在java中使用另一个堆栈来反转堆栈的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您好我正在尝试使用另一个空堆栈来反转堆栈(我自己编码的堆栈)。由于某种原因,它无法正常工作。谁能帮我这个 ?
Hi I am trying to reverse a stack(one I coded myself) using another empty stack. For some reason it is not working properly. Can anyone help me with this ?
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());
}
推荐答案
while(!stack1.isEmpty()){
Integer value = (Integer)stack1.pop();
System.out.println(value);
reverse.push(value);
}
这篇关于如何在java中使用另一个堆栈来反转堆栈的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文