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。