The Stack represents a collection of last-in, first-out objects. Use the stack when you need last-in-first-out access to items. When you add an item to the list called a push element, when you remove an item from the list, itis called a pop-up element. The following table lists some common properties of Attribute Description Count Gets the number of elements contained in the Stack. The following table lists some common methods of Serial number Method name & description 1 Public virtual void Clear (); removes all elements from the Stack. 2 Public virtual bool Contains (object obj); determines whether an element is in Stack. 3 Public virtual object Peek (); returns the object at the top of the Stack without removing it. 4 Public virtual object Pop (); removes and returns the object at the top of the Stack. 5 Public virtual void Push (object obj); add an object to the top of the Stack. 6 Public virtual object [] ToArray (); copy Stack into a new array. The following example demonstrates the use of Stack: When the above code is compiled and executed, it produces the following results: 1.57.1. Methods and properties of the Stack class #
Stack
class:
Stack
. 1.57.2. Example #
Example #
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 + " ");
}
}
}
}
Current stack:
W G M A
The next poppable value in stack: H
Current stack:
H V W G M A
Removing values
Current stack:
G M A