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等方法。

二、操作

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()

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

arr= nums.ToArray();

三、示意图

image

image

posted on 2018-08-06 09:33  springsnow  阅读(1047)  评论(0编辑  收藏  举报

导航