使用進棧和出棧操作實現堆疊的 C# 程式


使用進棧操作設定具有向堆疊新增元素功能的堆疊 −

Stack st = new Stack();

st.Push('A');
st.Push('M');
st.Push('G');
st.Push('W');

若要從堆疊彈出元素,請使用 Pop() 方法 −

st.Pop();
st.Pop();

以下示例演示了使用進棧和出棧操作實現堆疊 −

示例

 即時演示

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

更新於:2020-06-20

596 次瀏覽

開啟您的 職業生涯

完成課程,獲得認證

開始
廣告
© . All rights reserved.