Intern
What is a stack?
sobes.tech AI
Answer from AI
Stack is a data structure that operates on the Last-In, First-Out (LIFO) principle. Elements are added and removed only from one end, called the top of the stack.
Main operations:
- Push: Add an element to the top of the stack.
- Pop: Remove and return the element from the top of the stack.
- Peek: Return the element from the top of the stack without removing it.
- IsEmpty: Check if the stack is empty.
Examples of usage in C#:
- Managing function calls (call stack).
- Processing expressions (e.g., converting infix notation to postfix).
- Implementing graph and tree traversal algorithms (DFS).
- Undo/redo actions in applications.
In .NET, there is a class Stack<T> in the System.Collections.Generic namespace.
// Creating a stack of integers
System.Collections.Generic.Stack<int> numbers = new System.Collections.Generic.Stack<int>();
// Adding elements
numbers.Push(1);
numbers.Push(2);
numbers.Push(3); // Top of the stack
// Getting the top element without removing
int topElement = numbers.Peek(); // topElement will be 3
// Removing elements
int poppedElement = numbers.Pop(); // poppedElement will be 3
poppedElement = numbers.Pop(); // poppedElement will be 2
// Checking if empty
bool isEmpty = numbers.Count == 0; // isEmpty will be false
// Removing the last element
poppedElement = numbers.Pop(); // poppedElement will be 1
// Checking if empty after removing all elements
isEmpty = numbers.Count == 0; // isEmpty will be true