IAbstract
IAbstract

Reputation: 19881

Is new Stack<T>(curStack) returns reverse stack a bug?

This would appear to be a bug. Consider the following: stack order: skip skip match

... then:
stack order: match skip skip

After doing some checking, I found this answer as to some 'reversal' in stack order.

Wouldn't it be proper to expect the second stack to be in the same order as the original?
Is this a bug?

Upvotes: 2

Views: 74

Answers (2)

Theraot
Theraot

Reputation: 40230

It's by design.

Notice that the constructor overload of Stack<T> that you are using expects a IEnumerable<T>. The way it works is by iterating over the IEnumarable<T> and adding the items to the Stack.

Now, you are passing another Stack<T> as parameter. The way IEnumerable<T> is expected to behave is by giving the items in the order they would come when you take them from the Stack (That is LIFO: Last-In First-Out).

So, in fact, this operations are expected to reverse the stack.

Upvotes: 2

Servy
Servy

Reputation: 203827

No, it's not a bug.

A stack will yield the most recently added item first. So when you go to populate the new stack you're adding the newest item first. Since this item is added first it will now be the "oldest" item in the new stack, even though it was the "newest" item in the old stack.

The reversing is entirely expected behavior.

If you had a queue, then writing var newQueue = new Queue<T>(oldQueue); would effectively create a copy. Queues yield the oldest item first, so the oldest item in the old queue becomes the oldest item in the new queue. The same would be true of a list as well.

You seem to be under the impression that there is some sort of copy constructor, in which the stack takes another stack and makes a copy. This is untrue, it simply accepts an IEnumerable<T> as its input. For List and Queue this has the effect of taking a copy, for stacks is simply has the effect of reversing the items.

Upvotes: 6

Related Questions