سؤال

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 need some kind of random access to your structure, you might want to consider writing a wrapper around a structure that gives you random access in such a way that you can still operate on it as a stack, but be able to perform random access if needed.

The simplest answer would be a wrapper around a linked list. While it doesn't have random access (you would need to iteratively search through the list), it would provide the basic functionality you need and would be quite easy to implement your own wrapper around it for stack-like functionality.

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