# Thread: Reversing order of items in a stack

1. Member
Join Date
Feb 2011
Posts
53
Rep Power
0

## 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
Java 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.

2. ## 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.

3. ## 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.

4. Member
Join Date
Feb 2011
Posts
53
Rep Power
0

## 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.

5. ## 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.

6. ## 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.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•