A stack is a data structure in C# that allows you to store and retrieve elements in a Last-In-First-Out (LIFO) fashion. In other words, components are added to the stack’s top and deleted from the stack’s top. In contrast, a queue allows you to store and retrieve elements in a First-In-First-Out (FIFO) fashion.
In C#, the Stack class includes several methods for interacting with stacks, including the following.
- Push(): Adds an element to the stack’s top.
- Pop(): Removes and returns the top-most member of the stack.
- Peek() returns the top-most member of the stack without removing it.
- Count: Returns the number of stack elements.
Here’s an example of how the Stack class may be used to store and retrieve elements:
// Create a new stack. Stack<int> val= new Stack<int>(); // Add some elements to the stack. val.Push(2); val.Push(4); val.Push(6); // Print the number of elements in the val. Console.WriteLine(val.Count); // Output: 3 // Peek at the top element in the val. Console.WriteLine(val.Peek()); // Output: 3 // Pop an element from the top of the val. int valpopped = val.Pop(); Console.WriteLine(valpopped ); // Output: 3 // Print the number of elements in the val. Console.WriteLine(val.Count); // Output: 2
Stacks are frequently used in computer applications to store temporary data or data that must be processed in a particular sequence. A stack, for example, could be used by a web browser to save the pages that a user has seen so that they can be conveniently accessible by clicking the “back” button.
Another common application for stacks is in the implementation of recursive algorithms. Recursive algorithms are algorithms that constantly call themselves until a given condition is met. A stack is frequently used to store intermediate results in order to maintain track of the state of the algorithm at each stage of the recursion.