The Stack class represents a last-in-first-out collection of objects. You can use this when you need LIFO access to your project.
The following are the properties of the Stack class -
Use the following command to add an element in the stack Push operation-
Stack st = new Stack(); st.Push('A'); st.Push('B'); st.Push('C'); st.Push('D');
Pop operation from the stack Elements at the top start removing elements.
The following example shows how to use the Stack class and its Push( ) and Pop() methods -
Using System; using System.Collections; namespace CollectionsApplication { class Program { static void Main(string[] args) { Stack st = new Stack(); st.Push('A'); st.Push('B'); st.Push('C'); st.Push('D'); Console.WriteLine("Current stack: "); foreach (char c in st) { Console.Write(c + " "); } Console.WriteLine(); st.Push('P'); st.Push('Q'); 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 + " "); } } } }
The above is the detailed content of Push and pop in stack class in C#. For more information, please follow other related articles on the PHP Chinese website!