要从集合创建堆栈,代码如下-
using System; using System.Collections.Generic; public class Demo { public static void Main(){ Stack<int> stack = new Stack<int>(); stack.Push(100); stack.Push(200); stack.Push(300); stack.Push(400); stack.Push(500); stack.Push(600); stack.Push(700); stack.Push(800); stack.Push(900); stack.Push(1000); Console.WriteLine("Stack elements..."); foreach(int val in stack){ Console.WriteLine(val); } Console.WriteLine("\nArray elements..."); Stack<int> arr = new Stack<int>(stack.ToArray()); foreach(int val in arr){ Console.WriteLine(val); } } }
输出结果
Stack elements... 1000 900 800 700 600 500 400 300 200 100 Array elements... 100 200 300 400 500 600 700 800 900 1000
现在让我们来看另一个示例-
using System; using System.Collections.Generic; public class Demo { public static void Main(){ Stack<string> stack = new Stack<string>(); stack.Push("Katie"); stack.Push("Andy"); stack.Push("Ariane"); stack.Push("Justin"); Console.WriteLine("Stack elements..."); foreach(string val in stack){ Console.WriteLine(val); } Console.WriteLine("\nArray elements..."); Stack<string> arr = new Stack<string>(stack.ToArray()); foreach(string val in arr){ Console.WriteLine(val); } } }
输出结果
这将产生以下输出-
Stack elements... Justin Ariane Andy Katie Array elements... Katie Andy Ariane Justin