Stack is a LIFO(last-in, first out) collection of objects. It’s generic type that is part of System.Collections.Generic. You can read more about generics in my last post. There are three most important methods in this class: Peek(),Pop(),Push(). First lets explain the LIFO concept.
Great example of LIFO visualization is a stack of plates. When new plate is added its stored on the top of the stack, and when we want to remove a plate we can only grab the top one. Same idea is used in programming. Using this concept we can push the items into a stack and get it in reverse order. Stack returns the last item first. As elements are added to a Stack, the capacity is automatically increased as required through reallocation.Now lets see the class syntax and implementations of the methods.
Class signature is similar to other generic collections. You can find more about them here. We need to specify the type of the variable that will be stored in the collection.
Stack<string> numbers = new Stack<string>();
Let’s look at the methods
Push()
First we need to add items to our stack, to do this we will use Push() method
class Program { static void Main() { Stack<int> stack = new Stack<int>(); stack.Push(1); stack.Push(2); stack.Push(3); foreach (int i in stack) { Console.WriteLine(i); } } }
Output:
3
2
1
Push method adds elements to he top of the stack, elements are printed in reverse order.
Pop() and Peek()
when we have elements in our stack we can now return them with Pop() method, this will delete item from stack. If we want to copy the value, leaving it on the top of the stack we use Peek() method.
static void Main() { int pop = stack.Pop(); Console.WriteLine(pop); int peek = stack.Peek(); Console.WriteLine("Element at the top:"); Console.WriteLine(peek); }
Output:
3
Element at the top:2
Now you can add and remove items from stack. Stack can be useful for simulating for example deck of cards. In next article I’ll cover similar type called queue. Stay Awesome!