C#棧的簡單介紹


    棧(Stack)代表了一個只有一個出口的后進先出的對象集合。在列表中添加一項,稱為推入元素,從列表中移除一項時,稱為彈出元素。

    Stack<T> 類

    public class Stack<T> : IEnumerable<T>, ICollection, IEnumerable

  • 屬性

    Count  獲取 Stack 中包含的元素個數

  • 方法

    Pop   移除並返回在 Stack 的頂部的對象

    push  向 Stack 的頂部添加一個對象

    peek  返回在 Stack 的頂部的對象,但不移除它

    ToArray  創建數組並將堆棧元素復制到其中

    Contains   判斷一個元素是否在棧中

    Clear  從 Stack 中移除所有的元素。

  • 實例

在此使用MSDN中例子。以下代碼及結果顯示圖片來自:C#棧的簡單介紹及應用

using System; 

using System.Collections.Generic; 
class Example 

    public static void Main() 
    { 
        Stack<string> numbers = new Stack<string>(); 
        numbers.Push("one"); 
        numbers.Push("two"); 
        numbers.Push("three"); 
        numbers.Push("four"); 
        numbers.Push("five"); 
        // 遍歷元素 
        Console.ForegroundColor = ConsoleColor.Green; 
        foreach (string number in numbers) 
        { 
            Console.WriteLine(number); 
        } 
        //pop彈出元素,並刪除“five” 
        Console.WriteLine("\nPopping '{0}'", numbers.Pop()); 
       //peek彈出元素,但不刪除 
        Console.WriteLine("Peek at next item to destack: {0}",numbers.Peek()); 
       //再彈出再刪除 
        Console.WriteLine("Popping '{0}'", numbers.Pop()); 
       // 創建新棧,復制元素 
        Stack<string> stack2 = new Stack<string>(numbers.ToArray()); 
        Console.ForegroundColor = ConsoleColor.Magenta; 
        Console.WriteLine("\nContents of the first copy:"); 
        foreach (string number in stack2) 
        { 
            Console.WriteLine(number); 
        } 
        // 創建雙倍size數組,從一般開始存儲棧元素 
        string[] array2 = new string[numbers.Count * 2]; 
        numbers.CopyTo(array2, numbers.Count); 
        // 再創建雙倍size棧,將數組再存入 
        Stack<string> stack3 = new Stack<string>(array2); 
        Console.ForegroundColor = ConsoleColor.Yellow; 
        Console.WriteLine("\nContents of the second copy, with duplicates and nulls:"); 
        foreach (string number in stack3) 
        { 
            Console.WriteLine(number); 
        } 
       //contains用法 
        Console.WriteLine("\nstack2.Contains(\"four\") = {0}", stack2.Contains("four")); 
        Console.WriteLine("\nstack2.Clear()"); 
       //Clear()用法 
        stack2.Clear(); 
        Console.WriteLine("\nstack2.Count = {0}", stack2.Count); 
    } 
}

結果如下:

image

 


免責聲明!

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



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