how do I reverse a stack using another stack in java [closed]

北城以北 提交于 2019-12-31 05:41:09

问题


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());
    }

回答1:


 while(!stack1.isEmpty()){
        Integer value = (Integer)stack1.pop();
        System.out.println(value);
        reverse.push(value);
 }


来源:https://stackoverflow.com/questions/42914899/how-do-i-reverse-a-stack-using-another-stack-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!