Stack is a Simple DataStucture which allows Insert/Remove of Items at one end. It is basically called as LIFO (Last In First Out) data structure (i.e. the item which is added last is the first one to be removed) .NET has a built in class for Stack. It is found in the System.Collections namespace.
1. How to Create a Stack?
32 is the intial size of the Stack. It is always better to give intially size so that the Push/Pop operations are performed efficiently with out re-arranging the elements.
2. To Push a element to the Stack?
Push will place an element on the top of stack and also the element which is to be removed first.
3. How to Pop an Element?
Pop will return the recently push item in the stack. It throws Exception when the Stack is Empty.
4. What if i need to just see the Top element without removing it from the Stack?
Stack class has a method called Peek() which return the top element of the Stack. It is very similar to Pop() except that it would not remove the element from the Stack.
Stack類代碼:
using System;
//using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace StackHelper
{
class StackHelper
{
private Stack list;
public Stack List
{
set { list = value; }
get { return list; }
}
public StackHelper()
{
list = new Stack();//注意:不是list=new StackHelper()
Console.WriteLine("---------Stack-----------");
}
//壓入一個元素
public void Add(object o)
{
list.Push(o);
Console.WriteLine("壓入/t元素:{0}",o);
}
//刪除棧頂元素
public void Remove()
{
list.Pop();
Console.WriteLine("彈出棧頂元素");
}
//取出棧頂元素
public void GetValue()
{
list.Peek();
Console.WriteLine("取出棧頂元素的值");
}
//使用foreach進行遍曆
public void GetValues()
{
Console.WriteLine("遍曆");
foreach (object o in list)
{
Console.WriteLine(string.Format("/t元素的值:{0}",o));
}
}
//得到Stack的資訊
public void GetInfo()
{
Console.WriteLine(string.Format("資訊/t元素總數:{0}",list.Count));
}
}
}
測試頁面代碼:
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace StackHelper
{
class Program
{
static void Main(string[] args)
{
StackHelper list=new StackHelper();
list.Add("a");
list.Add("b");
list.Add("c");
list.GetInfo();
list.GetValues();
list.GetValue();
list.GetValues();
list.GetInfo();
list.Remove();
list.GetValues();
list.GetInfo();
}
}
}
注意:Pop ()和Peek()方法的區別。Pop()取出棧頂元素,棧頂元素被彈出Stack;Peek()讀得棧頂元素,但站定元素沒有被彈出Stack。