سؤال

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

هل كانت مفيدة؟

المحلول

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);

نصائح أخرى

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)

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top