【问题标题】:how do I reverse a stack using another stack in java [closed]java - 如何在java中使用另一个堆栈来反转堆栈[关闭]
【发布时间】: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 我已更新答案以包含值的输出。

标签: java stack


【解决方案1】:
 while(!stack1.isEmpty()){
        Integer value = (Integer)stack1.pop();
        System.out.println(value);
        reverse.push(value);
 }

【讨论】:

    猜你喜欢
    • 2011-10-05
    • 1970-01-01
    • 2016-05-06
    • 2015-04-22
    • 1970-01-01
    • 1970-01-01
    • 2021-08-13
    • 2011-08-10
    • 2020-10-12
    相关资源
    最近更新 更多