c语言enqueue用法,C# Queue.Enqueue()用法及代码示例

本文介绍了C#中Queue类的Enqueue方法,用于将对象添加到队列的末尾。当Count小于内部数组容量时,该操作为O(1),否则为O(n)。通过示例代码展示了如何使用Enqueue方法向队列添加元素并显示队列的元素数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

此方法用于将对象添加到队列的末尾。这属于System.Collections命名空间。该值可以为null,并且如果Count小于内部数组的容量,则此方法是O(1)操作。如果需要重新分配内部数组以容纳新元素,则此方法将成为O(n)操作,其中n是Count。

用法:

public virtual void Enqueue (object obj);

在这里,obj是添加到队列中的对象。

例:

// C# code to illustarte the

// Queue.Enqueue() Method

using System;

using System.Collections;

class GFG {

// Driver code

public static void Main()

{

// Creating a Queue

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

参考:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值