Simon
Simon

Reputation: 351

How can I copy a Stack<T> such that the copy is in the same order?

I am copying a Stack<string> where I use the constructor with the IEnumerable<T> collection parameter. When inspecting the resulting code, the order of the items are different.

Here is some code:

var stack = new Stack<string>();
stack.Push("value 1");
stack.Push("value 2");
stack.Push("value 3");
var stack2 = new Stack<string>(stack);
var pop1 = stack.Pop();
//pop1 is "value 3"
var pop2 = stack2.Pop();
//pop2 is "value 1"

How can I copy a Stack<T> such that the copy has it's items in the same order?

Upvotes: 1

Views: 526

Answers (2)

paxdiablo
paxdiablo

Reputation: 881623

Enumerating a stack pulls off the items in the reverse order you put them on (it's basically like a series of pop calls but without actually removing the data from the original stack):

If you then use that order to populate a new stack, the order will be reversed, as shown below:

Old           New
 1             3
 2             2
 3             1
 v             ^
 |             |
 +-- 3, 2, 1 --+

There may be an better way to do this but you could simply use a temporary stack so that there are two reversals, effectively giving you the same order in the final target:

var stack2 = new Stack<string>(new Stack<string>(stack));

This would give:

Old                                 New
===                                 ===
 1                 3                 1
 2                 2                 2
 3             +-> 1 >-+             3
 v             |       |             ^
 |             |       |             |
 +-- 3, 2, 1 --+       +-- 1, 2, 3 --+

Upvotes: 1

ProgrammingLlama
ProgrammingLlama

Reputation: 38767

Solution

You could probably make use of LINQ's Reverse() method:

var stack2 = new Stack<string>(stack.Reverse());

This should have the effect of reversing the enumerable from the first stack such that it is pushed into the new stack in reverse.

Explanation

You're using the Stack(IEnumerable<T>) constructor to create the new stack. Internally it is iterating that enumerable and pushing each item onto the stack.

The enumerable for Stack<T> yields the items in the "pop order" (i.e. 3, 2, 1), so it ends up pushing the items onto the new stack in the opposite order.

Upvotes: 1

Related Questions