C# 堆疊(Stack)
堆疊(Stack)代表了一個後進先出的對象集合。當您需要對各項進行後進先出的訪問時,則使用堆疊。當您在列表中添加一項,稱為推入元素,當您從列表中移除一項時,稱為彈出元素。
Stack 類的方法和屬性
下表列出了 Stack 類的一些常用的 屬性:
屬性 | 描述 |
---|---|
Count | 獲取 Stack 中包含的元素個數。 |
下表列出了 Stack 類的一些常用的 方法:
序號 | 方法名 & 描述 |
---|---|
1 | public virtual void Clear();
從 Stack 中移除所有的元素。 |
2 | public virtual bool Contains(
object obj
);
判斷某個元素是否在 Stack 中。 |
3 | public virtual object Peek(); 返回在 Stack 的頂部的對象,但不移除它。 |
4 | public virtual object Pop(); 移除並返回在 Stack 的頂部的對象。 |
5 | public virtual void Push(
object obj
); 向 Stack 的頂部添加一個對象。 |
6 | public virtual object[] ToArray(); 複製 Stack 到一個新的數組中。 |
實例
下麵的實例演示了堆疊(Stack)的使用:
實例
using System;
using System.Collections;
namespace CollectionsApplication
{
class Program
{
static void Main(string[] args)
{
Stack st = new Stack();
st.Push('A');
st.Push('M');
st.Push('G');
st.Push('W');
Console.WriteLine("Current stack: ");
foreach (char c in st)
{
Console.Write(c + " ");
}
Console.WriteLine();
st.Push('V');
st.Push('H');
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 + " ");
}
}
}
}
using System.Collections;
namespace CollectionsApplication
{
class Program
{
static void Main(string[] args)
{
Stack st = new Stack();
st.Push('A');
st.Push('M');
st.Push('G');
st.Push('W');
Console.WriteLine("Current stack: ");
foreach (char c in st)
{
Console.Write(c + " ");
}
Console.WriteLine();
st.Push('V');
st.Push('H');
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 + " ");
}
}
}
}
當上面的代碼被編譯和執行時,它會產生下列結果:
Current stack: W G M A The next poppable value in stack: H Current stack: H V W G M A Removing values Current stack: G M A