好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

C#中的队列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() CopyTo():把元素从队列复制到一个已有的数组中。 ToArray():返回一个包含队列元素的新数组。

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

三、示意图

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

查看更多关于C#中的队列Queue<T>与堆栈Stack<T>的详细内容...

  阅读:46次