C# - Stack 类

它表示一个后进先出的对象集合。当需要后进先出访问元素时,可以使用它。在列表中添加元素时,称为"入栈",移除元素时,称为"出栈"。

Stack 类的方法和属性

下表列出了 Stack 类的一些常用属性 -

序号 属性 &说明
1 Count

获取 Stack 中包含的元素数量。

下表列出了 Stack 类的一些常用方法 -

Sr.No. 方法 &说明
1 public virtual void Clear();

从堆栈中移除所有元素。

2 public virtual bool Contains(object obj);

判断元素是否在堆栈中。

3 public virtual void CopyTo (Array array, int index);

将堆栈复制到现有的一维数组。

4 public virtual object Clone();

创建堆栈的浅拷贝。

5 public virtual object Peek();

返回堆栈顶部的对象,但不将其移除。

6 public virtual object Pop();

移除并返回位于栈顶的对象。

7 public virtual void Push(object obj);

在栈顶插入一个对象。

8 public virtual object[] ToArray();

将栈复制到新的数组。

示例

以下示例演示了 Stack 的用法 -

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

csharp_collections.html