Stack中的流行元素范围

时间:2015-04-13 14:09:39

标签: c# stack

大家好我需要一些关于Stack.Pop()函数的小帮助。 据我所知,堆栈可以逐个弹出元素,但我需要弹出多个元素。例如,我在堆栈中有5个元素(4,3,2,1,0),现在我想弹出前3或2个元素,直到堆栈索引达到1或2。 现在我已经"因为"循环无法正常工作:

for(var i = stack.Count - 1; i >= 0; i--)
{
    stack.Pop();
}

有人可以帮帮我,让他弹出一定范围的元素吗? 谢谢!

4 个答案:

答案 0 :(得分:4)

如果你想弹出直到堆栈是一定的大小,只需使用

while(stack.Count > desiredCount)
    stack.Pop();

如果您想弹出一定数量的项目,请使用

for(int i=0; i < numberOfItemsToPop && stack.Count > 0; i++)
    stack.Pop();

答案 1 :(得分:2)

你可以使用简单的while循环来做这样的事情:

var stack = new Stack<int>(new[]{ 4, 3, 2, 1, 0 });

var numberToPop = 3;
while(numberToPop > 0 && stack.Count > 0)
{
    numberToPop--;
    stack.Pop();
}

答案 2 :(得分:2)

您还可以创建扩展方法:

public static class Extensions
{
    public static List<T> PopRange<T>(this Stack<T> stack, int amount)
    {
        var result = new List<T>(amount);
        while (amount-- > 0 && stack.Count > 0)
        {
            result.Add(stack.Pop());
        }
        return result;
    }
}

并在您想要的地方使用它:

var stack = new Stack<int>(new[] { 1, 2, 3, 4, 5 });

var result = stack.PopRange(3);

// result: { 5, 4, 3 }
//  stack: { 2, 1}

答案 3 :(得分:2)

您可以使用TryPopRange类的ConcurrentStack

示例:

var stack = new ConcurrentStack<int>(new[] { 1, 2, 3, 4, 5 });
var resultPop = new int[2]; //Assume that we want to pop only 2 items.
int startIndex = 0;
int endIndex = 1;

// The TryPopRange will pop 2 items from stack into resultPop.
if (stack.TryPopRange(resultPop, startIndex, endIndex) >= 1) //It returns the number of  popped item.
{
    Console.WriteLine($"This items has been popped: {string.Join(",", resultPop)}");
}
相关问题