首頁  >  文章  >  後端開發  >  C# 中堆疊類別中的壓入與彈出

C# 中堆疊類別中的壓入與彈出

WBOY
WBOY轉載
2023-08-27 11:05:04881瀏覽

C# 中堆栈类中的压入与弹出

Stack 類別表示物件的後進先出集合。當您需要對專案進行後進先出存取時,可以使用它。

以下是 Stack 類別的屬性 -

  • Count - 取得堆疊中的元素數量。

推送操作

使用以下命令在堆疊中新增元素推送操作-

Stack st = new Stack();

st.Push('A');
st.Push('B');
st.Push('C');
st.Push('D');

Pop 操作

Pop 操作從堆疊頂部的元素開始刪除元素。

下列範例顯示如何使用 Stack 類別及其 Push( ) 和 Pop() 方法 -

Using System;
using System.Collections;

namespace CollectionsApplication {
   class Program {
      static void Main(string[] args) {
         Stack st = new Stack();

         st.Push('A');
         st.Push('B');
         st.Push('C');
         st.Push('D');

         Console.WriteLine("Current stack: ");
         foreach (char c in st) {
            Console.Write(c + " ");
         }
         Console.WriteLine();

         st.Push('P');
         st.Push('Q');
         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 + " ");
         }
      }
   }
}

以上是C# 中堆疊類別中的壓入與彈出的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除