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>();
        return this;
        return revertStack;

Recommended Answers

All 9 Replies

first remark: change the next lines:



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

yes, you've done that. then you should be able to give us more information on where exactly it goes wrong.

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.

I did stack1.reverse();

and did you try the other one?

Fixed it

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.