棧(Stack)
棧中加入元素都是從上到下加入的,猶如住客棧一般
Pop :彈出棧頂元素並刪除
push :壓入棧頂元素
peek:彈出棧頂元素不刪除
ToArray:方法創建數組並將堆棧元素複製到其中
Contains:方法判斷一個元素是否在棧中
Stack<string> staA = new Stack<string>();
staA.Push("one");
staA.Push("two");
staA.Push("three");
staA.Push("four");
staA.Push("five");
foreach (string a in staA)//遍歷元素,將之變成string類型
{
Console.WriteLine(a);
}
//peek是把棧頂元素彈出(取出),但不刪除
Console.WriteLine("取出的元素是:{0}", staA.Peek());
//pop是把棧頂的元素彈出(取出),並將其刪除
Console.WriteLine("刪除的棧頂元素是:{0}",staA .Pop ());
//此時再輸出一次棧的元素,會發現five被刪除了
foreach (string b in staA)
{
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine(b);
}
//ToArray從棧底到棧頂將一個棧複製到另一個棧中
Stack<string> staB = new Stack<string>(staA.ToArray());
foreach (string c in staB)
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine(c);
}
Console.WriteLine(" ");
Console.ForegroundColor = ConsoleColor.DarkRed;
//contains方法,判斷一個元素是否在棧中
Console.WriteLine("six是否在棧中?");
Console.WriteLine(staA .Contains ("six"));
輸出結果如下: