栈和队列

 

栈是与队列非常类似的另一个容器,只是要使用不同的方法访问栈。最后添加到栈的元素会最先读取。栈是一个后进先出(LIFO)容器。

与Queue类相同,非泛型栈Stack也执行了ICollection、IEnumerable和ICloneable接口;泛型类Stack<T>实现了IEnumerable<T>、ICollection和IEnumerable接口。

 

队列是其元素以先进先出(FIFO)的方式来处理的集合。先放在队列中的元素会先读取。队列的例子有机场排的队、人力资源部中等待处理求职信的队列、打印队列中处理的打印任务、以循环方式等待CPU处理的线程。

在.NET的System.collections命名空间中有非泛型类Queue,在System.Collections.Generic命名空间中有泛型类Queue<T>。这两个类的功能非常类似,但泛型类型是强类型的,定义了类型T,而非泛型类基于Object类型。

在内部,Queue<T>类使用T类型的数组,这类似于List<T>类型。另一个类似之处是它们都执行ICollection和IEnumerable接口。Queue类执行了ICollection、IEnumerable和ICloneable接口。Queue<T>类执行了IEnumerable和ICloneable接口。Queue<T>泛型类没有执行泛型接口ICollection<T>,因为这个接口用Add()和Remove()方法定义了在集合添加和删除元素的方法。

队列与列表的主要区别是队列没有执行IList接口。所以不能用索引器访问队列。队列只允许添加元素,该元素会放在队列的尾部(使用Enqueue()方法),从队列的头部获取元素(使用Dequeue方法)。

Enqueue()方法在队列的一端添加元素,Dequeue()方法在队列的另一端读取和删除元素。用Dequeue()方法读取元素,将同时从队列中删除该元素。再调用一次Dequeue()方法,会删除会列中的下一项。

namespace Queue
{
    class Program
    {
        static void Main(string[] args)
        {
            Queue<Int32> intQueue = new Queue<Int32>();
            //填充队列
            for (int i = 0; i < 5; i++)
            {
                intQueue.Enqueue(i * 5);
            }

            //显示Queue
            Console.Write("intQueue values :\t");
            PrintValues(intQueue);

            //从队列中删除一个元素
            Console.WriteLine("\n(Dequeue)\t{0}", intQueue.Dequeue());

            //显示Queue
            Console.Write("intQueue values :\t");
            PrintValues(intQueue);


            //从队列中删除一另个元素
            Console.WriteLine("\n(Dequeue)\t{0}", intQueue.Dequeue());

            //显示Queue
            Console.Write("intQueue values :\t");
            PrintValues(intQueue);

            //查看第一个对象,但不删除它
            Console.WriteLine("\n(Peek)   \t{0}", intQueue.Peek());

            //显示Queue
            Console.Write("intQueue values :\t");
            PrintValues(intQueue);

            Console.ReadKey();
        }

        public static void PrintValues(IEnumerable<Int32> myCollection)
        {
            IEnumerator<Int32> myEnumerator = myCollection.GetEnumerator();
            while (myEnumerator.MoveNext())
            {
                Console.Write("{0} ", myEnumerator.Current);
            }
            Console.WriteLine();
        }

    }
}


 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值