-2

I want to reverse the stack so element at TOP should be at zero and vice versa. I know it may not be a right operation to do this but I want to do this. And if not I want to know why this not works

When I do

List<string> MyList = new List<string>();
MyList.Reverse()

It works. But not this one.

Stack<string> MyStack = new Stack<string>();
MyStack.Reverse()

Any Idea/ Solution??

Thanks & Regards,

Ganesh

Ganesh Satpute
  • 3,664
  • 6
  • 41
  • 78

2 Answers2

5

Assuming that MyListis of type List<T> and MyStackis of type Stack<T>:

List<T> defines a method named Reverse which reverses the order of the elements in the List [...] But Stack<T> does not define such a method. There is an extension method Enumerable.Reverse<T> that returns the elements in reversed order.

So you could try this:

MyStack = new Stack ( MyStack.Reverse() );

MSDN:

Update

As @Dennis_E mentioned in his answer and comment, calling above line of code would reverse the stack twice - meaning that MyStack will stay the same... So the correct answer is

MyStack = new Stack(MyStack);
Stephan Bauer
  • 9,120
  • 5
  • 36
  • 58
  • Combine this answer with mine and you've got it. MyStack.Reverse() will return the top item last and so the stack will be in the same order as it was. You need MyStack = new Stack(MyStack); – Dennis_E May 12 '14 at 09:17
0

A stack is already in reverse, so to speak. If you have a stack with items A,B & C, with A at the top, reverse() gives you C,B,A, but if you add those to a stack again, A will be on top again. (C will be added first, then B and then A)

Dennis_E
  • 8,751
  • 23
  • 29