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