C# Stack<T>
C# Stack<T>
C# Stack
类用于推送和弹出元素。它使用堆栈的概念以 LIFO(后进先出)顺序排列元素。它可以有重复的元素。它位于 System.Collections.Generic 命名空间中。
C# Stack
示例
让我们看一个存储元素的通用 Stack
类的示例使用 Push() 方法,使用 Pop() 方法移除元素并使用 for-each 循环迭代元素。
using System;
using System.Collections.Generic;
public class StackExample
{
public static void Main(string[] args)
{
Stack<string> names = new Stack<string>();
names.Push("Sonoo");
names.Push("Peter");
names.Push("James");
names.Push("Ratan");
names.Push("Irfan");
foreach (string name in names)
{
Console.WriteLine(name);
}
Console.WriteLine("Peek element: "+names.Peek());
Console.WriteLine("Pop: "+ names.Pop());
Console.WriteLine("After Pop, Peek element: " + names.Peek());
}
}
输出:
Sonoo
Peter
James
Ratan
Irfan
Peek element: Irfan
Pop: Irfan
After Pop, Peek element: Ratan