C# 程序实现带有 Push 和 Pop 操作的堆栈
csharpprogrammingserver side programming更新于 2025/9/23 4:23:00
使用 Push 操作设置堆栈以将元素添加到堆栈 −
Stack st = new Stack();
st.Push('A');
st.Push('M');
st.Push('G');
st.Push('W');
要从堆栈中弹出元素,请使用 Pop() 方法 −
st.Pop();
st.Pop();
以下是实现带有 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('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

