Is it possible to Peek at the value of a C# Stack variable
layers below the surface? In my example, I need to Peek at the value one below. I could Peek
to record the value into a temporary variable, Pop
and read, then Push
the temporary values back, but is there a better way?
A Stack
is also an IEnumerable
, so you can use the standard methods for manipulating those. For example, with the System.Linq
namespace open, you can write stack.Skip(1).First()
.
Consider using a linked list for this purpose. As with a stack, popping from it (using RemoveFirst
) is an O(1) operation, as is accessing the first element (peeking). Unlike a stack, you can also access the second element very easily with <stack object>.First.Next
in constant time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With