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

来源:这里教程网 时间:2026-02-21 16:16:56 作者:

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 + " ");
         }
      }
   }
}

相关推荐