为了使对象位于堆栈的顶部,代码如下-
using System;
using System.Collections.Generic;
public class Demo {
public static void Main() {
Stack<string> stack = new Stack<string>();
stack.Push("A");
stack.Push("B");
stack.Push("C");
stack.Push("D");
stack.Push("E");
stack.Push("F");
stack.Push("G");
stack.Push("H");
stack.Push("I");
stack.Push("J");
Console.WriteLine("元素的数量 = "+stack.Count);
Console.WriteLine("堆栈顶部的元素 = " + stack.Peek());
}
}输出结果
这将产生以下输出-
元素的数量 = 10 堆栈顶部的元素 = J 元素的数量 = 10
让我们看另一个例子-
using System;
using System.Collections.Generic;
public class Demo {
public static void Main() {
Stack<int> stack = new Stack<int>();
stack.Push(10);
stack.Push(20);
stack.Push(30);
stack.Push(40);
stack.Push(50);
stack.Push(60);
stack.Push(70);
stack.Push(80);
stack.Push(90);
stack.Push(100);
Console.WriteLine("元素的数量 = "+stack.Count);
Console.WriteLine("堆栈顶部的元素 = " + stack.Peek());
Console.WriteLine("堆栈顶部的元素 = " + stack.Peek());
}
}输出结果
这将产生以下输出-
元素的数量 = 10 堆栈顶部的元素 = 100 堆栈顶部的元素 = 100