-1

我们有 Enqueue 和 Dequeue 方法来处理 C# 中的队列。但是有没有办法我们可以删除队列中的最后一项?出队实际上是从顶部删除项目。

4

4 回答 4

1

a 的全部目的Queue是从上到下遍历集合。如果您想要一个允许从后面(或集合中的任何位置)移除的集合类型,请使用另一种集合类型,List<T>例如 a。

于 2016-03-08T14:20:00.983 回答
0

这是一项昂贵的手术,所以我很少这样做。这里的人生气而不回答......你所做的只是使用第二个队列将所有内容移动到:

// original queue must already be filled up
Queue<Waypoint> waypoints = new Queue<Waypoint>();
// fill it up...

Queue<Waypoint> temp = new Queue<Waypoint>();
while (waypoints.Count > 0) // stop one short of the end
{
    temp.Enqueue(waypoints.Dequeue());
}
Waypoint wp = waypoints.Dequeue();
// get the last one and do what you desire to it...
// I modified mine and then added it back, this is not needed
temp.Enqueue(new Waypoint(wp.pos, (p.vectorPath[0] - wp.pos).normalized));

// necessary: you have waypoints empty now so you have to  swap it for temp:
waypoints = temp;
于 2021-11-28T01:46:33.600 回答
0

也许您应该考虑使用堆栈而不是队列。

堆栈的工作方式类似于队列,但当您需要对象的后进先出解决方案时,使用堆栈而不是先进先出行为

于 2016-03-08T14:26:10.627 回答
-1

就像帕特里克所说的那样,队列是先进先出的。把它想象成一个打印机队列,进入打印机队列的第一页是第一个被打印出来的。

研究使用列表而不是数组,我发现使用数组没有的一堆扩展方法更容易操作列表。 http://www.dotnetperls.com/list

这是一个链接,指向如何删除列表中的最后一项,它有几种不同的方法来完成它。

如何删除添加到列表中的最后一个元素?

希望这可以帮助!

于 2016-03-08T14:39:40.570 回答