队列代表对象的先进先出集合。当您需要对项目进行先进先出的访问时,可以使用它。当您在列表中添加项目时,它称为enqueue ,而当您删除项目时,它称为dequeue 。
Queue
特性:
- Enqueue将元素添加到队列的末尾。
- 出队从队列开始处删除最旧的元素。
- Peek返回位于队列开始处的最旧元素,但不会将其从队列中删除。
- 队列的容量是队列可以容纳的元素数。
- 随着元素添加到队列中,通过重新分配内部数组,容量会根据需要自动增加。
- 队列接受null作为引用类型的有效值,并允许重复的元素。
句法 :
void Enqueue(object obj);
Enqueue()方法将值插入到队列的末尾。
例子:
// C# code to add an object
// to the end of the Queue
using System;
using System.Collections.Generic;
class GFG {
// Driver code
public static void Main()
{
// Creating a Queue of strings
Queue myQueue = new Queue();
// Inserting the elements into the Queue
myQueue.Enqueue("one");
// Displaying the count of elements
// contained in the Queue
Console.Write("Total number of elements in the Queue are : ");
Console.WriteLine(myQueue.Count);
myQueue.Enqueue("two");
// Displaying the count of elements
// contained in the Queue
Console.Write("Total number of elements in the Queue are : ");
Console.WriteLine(myQueue.Count);
myQueue.Enqueue("three");
// Displaying the count of elements
// contained in the Queue
Console.Write("Total number of elements in the Queue are : ");
Console.WriteLine(myQueue.Count);
myQueue.Enqueue("four");
// Displaying the count of elements
// contained in the Queue
Console.Write("Total number of elements in the Queue are : ");
Console.WriteLine(myQueue.Count);
myQueue.Enqueue("five");
// Displaying the count of elements
// contained in the Queue
Console.Write("Total number of elements in the Queue are : ");
Console.WriteLine(myQueue.Count);
myQueue.Enqueue("six");
// Displaying the count of elements
// contained in the Queue
Console.Write("Total number of elements in the Queue are : ");
Console.WriteLine(myQueue.Count);
}
}
输出:
Total number of elements in the Queue are : 1
Total number of elements in the Queue are : 2
Total number of elements in the Queue are : 3
Total number of elements in the Queue are : 4
Total number of elements in the Queue are : 5
Total number of elements in the Queue are : 6
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.generic.queue-1.enqueue?view=netframework-4.7.2#System_Collections_Generic_Queue_1_Enqueue__0_