C# Stack with Examples

Stack with Examples

A Stack<T> is a collection that represents a last-in-first-out (LIFO) set of objects. It's part of the System.Collections.Generic namespace in C#. The main operations offered by a stack are Push to insert an item, and Pop to remove the most recently added item.

Here's a tutorial on Stack<T> in C# with examples:

1. Creating a Stack

To work with a generic stack, make sure you've imported the necessary namespace:

using System.Collections.Generic; 

Now, initialize a Stack:

Stack<int> numbers = new Stack<int>(); 

2. Adding Elements

To add an item to the stack, use the Push method:

numbers.Push(1); numbers.Push(2); numbers.Push(3); 

3. Removing and Retrieving Elements

To remove and retrieve the item at the top of the stack, use the Pop method:

int top = numbers.Pop(); // top will be 3 

To only retrieve the item at the top without removing it, use Peek:

int currentTop = numbers.Peek(); // currentTop will be 2 

4. Checking the Stack

  • To check if the stack contains a particular item:
bool hasTwo = numbers.Contains(2); // Returns true 
  • To get the number of items:
int count = numbers.Count; // count will be 2 after the previous operations 

5. Iterating Over a Stack

You can use a foreach loop to iterate through the stack:

foreach (int number in numbers) { Console.WriteLine(number); } 

Remember, since it's a stack, the iteration will start from the top item and proceed downwards.

6. Clearing a Stack

To remove all items:

numbers.Clear(); 

Example: Checking for Balanced Parentheses with a Stack

A classic use case for stacks is to check for balanced parentheses in a string:

using System; using System.Collections.Generic; class Program { static bool AreParenthesesBalanced(string expression) { Stack<char> stack = new Stack<char>(); foreach (char ch in expression) { if (ch == '(') { stack.Push(ch); } else if (ch == ')') { if (stack.Count == 0 || stack.Pop() != '(') { return false; } } } return stack.Count == 0; } static void Main() { string expression = "(1 + 2) * (3 / 4)"; if (AreParenthesesBalanced(expression)) { Console.WriteLine("The parentheses are balanced."); } else { Console.WriteLine("The parentheses are not balanced."); } } } 

Conclusion

The Stack<T> collection in C# is an essential tool when you need a LIFO data structure. Whether it's for parsing expressions, backtracking algorithms, or various other tasks, stacks offer a straightforward way to manage your data.


More Tags

android-mapview hashlib keyword-argument spring-security-oauth2 pdfmake cors elm lazy-evaluation django-media electron-builder

More Programming Guides

Other Guides

More Programming Examples