how do I reverse a stack using another stack in ja

2019-03-04 15:08发布

问题:

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


标签: java stack