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 年 6 月 20 日

598 次觀看

開啟您的職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.