C # stack (Stack)
Stack (Stack)LIFO represents a collection of objects.When you need to perform the LIFO access, use the stack. When you add a list, called apush element when you remove the item from the list, called the popelement.
Stack methods and properties of the class
The following table lists some of the commonattributes Stackclass:
属性 | 描述 |
---|---|
Count | 获取 Stack 中包含的元素个数。 |
The following table lists some of the commonmethods Stackclass:
序号 | 方法名 & 描述 |
---|---|
1 | public virtual void Clear();
从 Stack 中移除所有的元素。 |
2 | public virtual bool Contains(
object obj
);
判断某个元素是否在 Stack 中。 |
3 | public virtual object Peek(); 返回在 Stack 的顶部的对象,但不移除它。 |
4 | public virtual object Pop(); 移除并返回在 Stack 的顶部的对象。 |
5 | public virtual void Push(
object obj
); 向 Stack 的顶部添加一个对象。 |
6 | public virtual object[] ToArray(); 复制 Stack 到一个新的数组中。 |
Examples
The following example demonstrates the stack (Stack) Use:
using System; using System.Collections; namespace CollectionsApplication { class Program { static void Main (string [] args) { Stack st = new Stack (); st.Push ( 'A'); st.Push ( 'M'); st.Push ( 'G'); st.Push ( 'W'); Console.WriteLine ( "Current stack:"); foreach (char c in st) { Console.Write (c + ""); } Console.WriteLine (); st.Push ( 'V'); st.Push ( 'H'); Console.WriteLine ( "The next poppable value in stack: {0}", st.Peek ()); Console.WriteLine ( "Current stack:"); foreach (char c in st) { Console.Write (c + ""); } Console.WriteLine (); Console.WriteLine ( "Removing values"); st.Pop (); st.Pop (); st.Pop (); Console.WriteLine ( "Current stack:"); foreach (char c in st) { Console.Write (c + ""); } } } }
When the above code is compiled and executed, it produces the following results:
Current stack: WGMA The next poppable value in stack: H Current stack: HVWGMA Removing values Current stack: GMA