# Reversing order of items in a stack

• 11-10-2011, 08:41 PM
trishtren
Reversing order of items in a stack
Hello, i am still studying stack algorithms and i am curious as to how to go about reversing the order of items in a stack. I have a stack filled with items like this
[1,2,3,4,5,6,7,8,9,10,11]
and when i pop obviously the order becomes
[11,10,9,87,6,5,4,3,2,1]

but i am looking to maintain the initial order of the stack when printing to the screen I.E when i pop, so is there an easy way to pop items from one stack, and add them to another in their original order using just push and pop?

I.E
Code:

``` for (int i=0;i < 10;i++)         {         stackex.push(numberlist.pop());         } do { System.out.print("order is"+stackex.pop()); }while(!stackex.empty()); //results in numbers going in opposite direction```
So any helping on maintaining the order of the original would be good.
• 11-10-2011, 10:10 PM
Shoss
Re: Reversing order of items in a stack
I'm confused as to what you're asking. You asked how to go about reversing the order of items in a stack, but then say you want to make a duplicate stack with the same order?

Why only push and pop? The clone() method creates an exact copy of the original stack in the same order.
• 11-10-2011, 11:19 PM
Junky
Re: Reversing order of items in a stack
Be careful if you use the clone method as it only does a shallow copy. Research deep versus shallow copy if you do not understand.
• 11-11-2011, 12:55 AM
trishtren
Re: Reversing order of items in a stack
hmm mainly i wanted to just use a for loop, i actually have achieved it by just copying the items into a temporary stack and then popping them out again causing them to go back in their original order, however thanks tons for you advise and i have read up on the clone method.
• 11-11-2011, 12:57 AM
Junky
Re: Reversing order of items in a stack
You still haven't explained what you are trying to do. If you want to retain the elements in the original order then why make changes at all. They are already in their original order.
• 11-11-2011, 02:43 AM
kjkrum
Re: Reversing order of items in a stack
It sounds like you don't want a stack at all, but a queue. Check out Deque (Java Platform SE 6), which you can use both ways.