C# - 堆疊類



它表示物件的先進先出集合。當您需要先進先出的專案訪問時,可以使用它。當您向列表中新增專案時,稱為推送專案;當您將其移除時,稱為彈出專案。

堆疊類的使用方法和屬性

下表列出了堆疊類的一些常用屬性

序號 屬性和描述
1

Count

獲取堆疊中包含的元素數量。

下表列出了堆疊類的一些常用方法

序號 方法和描述
1

public virtual void Clear();

移除堆疊中的所有元素。

2

public virtual bool Contains(object obj);

確定堆疊中是否存在元素。

3

public virtual object Peek();

返回堆疊頂部的物件,但不將其移除。

4

public virtual object Pop();

移除並返回堆疊頂部的物件。

5

public virtual void Push(object obj);

在堆疊頂部插入一個物件。

6

public virtual object[] ToArray();

將堆疊複製到一個新陣列。

示例

以下示例演示了堆疊的使用:

using System;
using System.Collections;

namespace CollectionsApplication {
   class Program {
      static void Main(string[] args) {
         Stack st = new Stack();
         
         st.Push('A');
         st.Push('M');
         st.Push('G');
         st.Push('W');
         
         Console.WriteLine("Current stack: ");
         foreach (char c in st) {
            Console.Write(c + " ");
         }
         Console.WriteLine();
         
         st.Push('V');
         st.Push('H');
         Console.WriteLine("The next poppable value in stack: {0}", st.Peek());
         Console.WriteLine("Current stack: ");
         
         foreach (char c in st) {
            Console.Write(c + " ");
         }
         
         Console.WriteLine();
         
         Console.WriteLine("Removing values ");
         st.Pop();
         st.Pop();
         st.Pop();
         
         Console.WriteLine("Current stack: ");
         foreach (char c in st) {
            Console.Write(c + " ");
         }
      }
   }
}

編譯並執行以上程式碼後,將產生以下結果:

Current stack: 
W G M A
The next poppable value in stack: H
Current stack: 
H V W G M A
Removing values
Current stack: 
G M A
csharp_collections.htm
廣告