2.Stack類
棧,後進先出。push方法入棧,pop方法出棧。
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace ConsoleApplication1
...{
class Program
...{
static void Main(string[] args)
...{
Stack sk = new Stack();
Stack sk2 = new Stack();
foreach (int i in new int[4] ...{ 1, 2, 3, 4 })
...{
sk.Push(i);//填充
sk2.Push(i);
}
foreach (int i in sk)
...{
Console.WriteLine(i);//遍歷
}
sk.Pop();
Console.WriteLine("Pop");
foreach (int i in sk)
...{
Console.WriteLine(i);
}
sk2.Peek();//彈出最後一項不刪除
Console.WriteLine("Peek");
foreach (int i in sk2)
...{
Console.WriteLine(i);
}
while (sk2.Count != 0)
...{
int i = (int)sk2.Pop();//清空
sk2.Pop();//清空
}
Console.WriteLine("清空");
foreach (int i in sk2)
...{
Console.WriteLine(i);
}
}
}
}
圖2
3.Queue類
隊列,先進先出。enqueue方法入隊列,dequeue方法出隊列。
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace ConsoleApplication1
...{
class Program
...{
static void Main(string[] args)
...{
Queue qu = new Queue();
Queue qu2 = new Queue();
foreach (int i in new int[4] ...{ 1, 2, 3, 4 })
...{
qu.Enqueue(i);//填充
qu2.Enqueue(i);
}
foreach (int i in qu)
...{
Console.WriteLine(i);//遍歷
}
qu.Dequeue();
Console.WriteLine("Dequeue");
foreach (int i in qu)
...{
Console.WriteLine(i);
}
qu2.Peek();//彈出最後一項不刪除
Console.WriteLine("Peek");
foreach (int i in qu2)
...{
Console.WriteLine(i);
}
while (qu2.Count != 0)
...{
int i = (int)qu2.Dequeue();//清空
qu2.Dequeue();//清空
}
Console.WriteLine("清空");
foreach (int i in qu2)
...{
Console.WriteLine(i);
}
}
}
}
圖3