隊列Queue FIFO先進先出 棧Stack FILO先進后出


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //隊列的特點就是先進先出
            Queue<string> queue = new Queue<string>();
            queue.Enqueue("張三");   //入隊  將對象添加到 System.Collections.Generic.Queue<T> 的結尾處。
            queue.Enqueue("李四");
            queue.Enqueue("王五");

            int queueCount = queue.Count(); //返回序列中元素的數量

            string name = queue.Dequeue(); //出隊 把隊首的元素移除,並將這移除的元素返回。
            Console.WriteLine(name); //輸出“張三” 

            name = queue.Dequeue(); //因為“張三”已經被移除了。所以現在是“李四”是在隊首了
            Console.WriteLine(name); //輸出“李四”

            name = queue.Dequeue(); //因為“李四”也被移除了,所以隊列中就只剩下王五了。
            Console.WriteLine(name); //輸出“王五”

           
            //------------------------------------------------------------

            //棧的特點就是先進后出(了解下就可以了,用的不多)
            Stack<string> stack = new Stack<string>();
            stack.Push("張三"); //入棧, 將對象插入 System.Collections.Generic.Stack<T> 的頂部。
            stack.Push("李四"); 
            stack.Push("王五");

            int stackCount= stack.Count(); //返回棧中的數量
            string name1 = stack.Pop(); //出棧。把棧首的元素移除,並將移除的元素返回。
            Console.WriteLine(name); //輸出:“王五”

            name1 = stack.Pop();
            Console.WriteLine(name1);//輸出:“李四”

            
            name1 = stack.Pop();
            Console.WriteLine(name1);//輸出:“張三”

            
            //name1 = stack.Peek(); //這是返回棧首的對象,但是不將它移除
            Console.ReadKey();

        }
    }
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM