亲宝软件园·资讯

展开

C#队列Queue<T>与堆栈Stack<T>

springsnow 人气:0

一、概述:

Queue<T>队列,对象的先进先出集合(“FIFO”)。Stack<T>栈,对象的后进先出集合(”LIFO”)。

Queue<T>、Stack<T>类似于List<T>,但 Queue<T>没有IList<T>,所以不能用索引访问队列。也没有实现ICollection<T>,无Add,Remove等方法。

二、操作

1、入队列:Enqueue()

Queue<string> nums = new Queue<string>();
nums.Enqueue("one");
nums.Enqueue("two");
nums.Enqueue("three");

2、入栈:Push()

Stack<string> nums = new Stack<string>();
nums.Push("one");
nums.Push("two");
nums.Push("three");

3、遍历:队列最先返回最先进的,栈最先返回最后进的元素。

foreach (var num in nums)//队列依次返回,one,two,three ;栈依次返回:three,two,one,
{
    Console.WriteLine(num);
}

4、出队列:Dequeue()返回最先进的元素。

Console.WriteLine(nums.Dequeue());//one

5、出栈:Pop()返回最后进的元素。

Console.WriteLine(nums.Pop());//three

6、返回开始处的元素:Peek()

Console.WriteLine(nums.Peek());//two

7、判断是否包含元素:Contains()

Console.WriteLine(nums.Contains("three"));

8、清空队列、栈:Clear()

nums.Clear();

9、队列、栈中元素个数:Count

Console.WriteLine(nums.Count);//0

10、复制到数组:CopyTo()、ToArray()

string[] arr=new string[3];
nums.CopyTo(arr,0);

arr= nums.ToArray();

三、示意图

image

image

加载全部内容

相关教程
猜你喜欢
用户评论