This method is supposed to reverse a stack by making a new stack and pushing popped items from this stack to the revertStack and then returning the reverted stack. When I run some tests, it returns an empty stack in stead. Any clues?

public LinkedStack<E> reversed()
{
    LinkedStack<E> revertStack = new LinkedStack<E>();
    if(this.isEmpty()==true){
        return this;
    }
    else{
        while(this.isEmpty()==false)
            {
            Node<E> snode=this.top;
            revertStack.push(snode.getData());
            this.pop();
            snode=snode.getLink();
            }
        return revertStack;
        }
    }

Edited 3 Years Ago by pritaeas: Moved to Java.

first remark: change the next lines:
if(this.isEmpty()==true){
while(this.isEmpty()==false)

to

if(this.isEmpty()){
while(!this.isEmpty())

less code means less chances to code something wrong.

have you debugged your code, or at least added some print statements to verify the code you expect to run is running with the values you wanted to see?

I've done that but I still get an empty stack when I revert a stack and print it out again

When I return the this stack in the revresed() method and try to use it on a stack in main, the stack is empty.

Suppose I create a generic LinkedStack<String> stack1 = LinkedStack<String>() object and populate it with 10 strings.
When I do stack1.reverse() and
System.out.println(stack1); it returns an empty stack1

What I want it to do is return a revresed copy of stack1.

in the reversed() method, this gets depopulated and a new method, gets populated. I want the this object in reversed() to reference the revertStack object before depopulation

Did you do

stack1.reverse(); // or whatever you named the method again

or did you do

stack1 = stack1.reverse();  // or whatever you named the method.

Hopefully you can see the difference, and, hopefully you now realize what difference that difference makes.

This question has already been answered. Start a new discussion instead.