C# 中 Stack 类中的 Push 与 Pop
Stack 类表示一个先进后出对象集合。当您需要一个先进后出的项访问时使用它。
以下为 Stack 类的属性 −
Count − 获取堆栈中的元素数。
Push 操作
使用 Push 操作在堆栈中添加元素 −
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 + " ");
}
}
}
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP