//
In this tutorial, we will explore the Stack data structure in C#. A stack is a linear data structure that follows the Last In First Out (LIFO) principle. This means that the last element added to the stack will be the first one to be removed. Stacks are commonly used in various applications such as expression evaluation, backtracking algorithms, and more.
A stack can be visualized as a vertical pile of plates where you can only add or remove the top plate. In C#, the Stack class is part of the System.Collections.Generic namespace and provides methods to push (add) and pop (remove) elements from the collection.
Let's dive into some practical examples to understand how to use the Stack collection in C#.
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Create a new Stack of integers
Stack<int> stack = new Stack<int>();
// Push elements onto the stack
stack.Push(10);
stack.Push(20);
stack.Push(30);
// Display the count of elements in the stack
Console.WriteLine($"Count: {stack.Count}");
// Peek at the top element without removing it
int topElement = stack.Peek();
Console.WriteLine($"Top Element: {topElement}");
// Pop elements from the stack
while (stack.Count > 0)
{
int poppedElement = stack.Pop();
Console.WriteLine($"Popped Element: {poppedElement}");
}
}
}
<OutputBlock>
{`Count: 3
Top Element: 30
Popped Element: 30
Popped Element: 20
Popped Element: 10`}
</OutputBlock>
### Example 2: Using Stack for Expression Evaluation
Stacks are often used in evaluating expressions, such as converting infix notation to postfix (Reverse Polish Notation) and then evaluating the postfix expression.
```csharp
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
string expression = "2 3 + 4 *";
Stack<int> stack = new Stack<int>();
foreach (string token in expression.Split(' '))
{
if (int.TryParse(token, out int number))
{
// If the token is a number, push it onto the stack
stack.Push(number);
}
else
{
// If the token is an operator, pop two numbers from the stack,
// perform the operation, and push the result back onto the stack
int operand2 = stack.Pop();
int operand1 = stack.Pop();
switch (token)
{
case "+":
stack.Push(operand1 + operand2);
break;
case "-":
stack.Push(operand1 - operand2);
break;
case "*":
stack.Push(operand1 * operand2);
break;
case "/":
stack.Push(operand1 / operand2);
break;
}
}
}
// The final result is the only element left in the stack
Console.WriteLine($"Result: {stack.Pop()}");
}
}
<OutputBlock>
{`Result: 26`}
</OutputBlock>
## What's Next?
In the next section, we will explore LINQ (Language Integrated Query) in C#, which provides a powerful way to query and manipulate data. Stay tuned!
<Tip variant="info">Remember, understanding data structures like stacks is crucial for building efficient algorithms and solving complex problems.</Tip>