C#(99):Queue<T>队列与Stack<T>堆栈

一、概述:

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

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

二、操作

入队列:Enqueue()

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

入栈:Push()

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

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

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

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

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

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

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

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

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

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

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

清空队列、栈:Clear()

nums.Clear();

队列、栈中元素个数:Count

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

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

  1. CopyTo():把元素从队列复制到一个已有的数组中。
  2. ToArray():返回一个包含队列元素的新数组。
string[] arr=new string[3];
nums.CopyTo(arr,0);

arr= nums.ToArray();

三、示意图

image

image

原文地址:https://www.cnblogs.com/springsnow/p/9428528.html