Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to Peek below the surface of a Stack?

Tags:

stack

c#

peek

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?

like image 484
Keavon Avatar asked Jan 01 '14 02:01

Keavon


2 Answers

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().

like image 192
GS - Apologise to Monica Avatar answered Sep 21 '22 22:09

GS - Apologise to Monica


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.

like image 36
Chris Laplante Avatar answered Sep 21 '22 22:09

Chris Laplante