Michael C
Michael C

Reputation: 9

Java - How do write a method to reverse one stack onto another without destroying the original stack?

So, I need to write a method to reverse stack1 onto stack2 using stack1.reverseStack(stack2). I need to do this without destroying stack1. This is what I have so far...

public void reverseStack(StackClass otherStack)
{
   int x = stackTop;

   for (int i = 0; i < x; i++)
   {
       otherStack.push(copy.top());
       copy.pop();
   }

}

It works only I can't figure out a way to not destroy stack1. I thought of making a copy stack and using that but I can't figure out how to copy stack1 in the method.

Upvotes: 0

Views: 2145

Answers (1)

Kal
Kal

Reputation: 24910

You can do this using an intermediate stack if thats allowed --

public void reverseStack(StackClass otherStack)
{
   StackClass newStack = new StackClass();

   StackObj obj = null;
   while ( (obj = this.pop()) != null ) {
              otherStack.push(obj);
              newStack.push(obj);
   }

   // Now push back from newStack to this stack
   while ( (obj = newStack.pop() ) != null ) {
             this.push(obj);
   }
}

Upvotes: 1

Related Questions