紀錄Stack用法,忘了回來查比較快
把Extension Method寫出來,用起來比較方便
public static class MyExtensions
{
public static void MyPush(this Stack<string> stack, string message)
{
stack.Push(message);
Console.WriteLine($"'Push'放入資料 : {message}");
stack.MyShow();
}
public static string MyPeek(this Stack<string> stack)
{
string lastData = stack.Peek();
Console.WriteLine($"'Peek'觀察資料 : {lastData}");
stack.MyShow();
return lastData;
}
public static string MyPop(this Stack<string> stack)
{
string lastData = stack.Pop();
Console.WriteLine($"'Pop'取出資料 : {lastData}");
stack.MyShow();
return lastData;
}
public static void MyShow(this Stack<string> stack)
{
string s = string.Join($"{Environment.NewLine}", stack);
Console.WriteLine("=====當前資料 : ======");
Console.WriteLine($"{s}");
Console.WriteLine("======================");
}
}
操作Stack
static void Main(string[] args)
{
Stack<string> data = new Stack<string>();
data.MyPush("資料A");
data.MyPush("資料B");
data.MyPush("資料C");
data.MyPush("資料D");
data.MyPeek();
data.MyPop();
data.MyPeek();
data.MyPush("資料E");
data.MyPop();
data.MyPop();
Console.ReadLine();
}
顯示結果 :
主要就是
1.Push => 加入資料在頂層
2.Peek => 觀察頂層資料(不取出)
3.Pop => 取出頂層資料
網路上看到的的圖(https://www.journaldev.com/21287/swift-stack-implementation)
大概94John