Generic collections part 2: Stack and Queue
Stack
A Stack is a linear data structure that follows the Last-In-First-Out (LIFO) principle. It's like a stack of plates: the last plate you put on is the first one you take off.
Key Operations:
Push: Adds an element to the top of the stack.
Pop: Removes and returns the element from the top of the stack.
Peek: Returns the element at the top of the stack without removing it.
IsEmpty: Checks if the stack is empty.
Example:
Stack<int> numberStack = new Stack<int>();
// Push elements onto the stack
numberStack.Push(10);
numberStack.Push(20);
numberStack.Push(30);
// Pop elements from the stack
int topNumber = numberStack.Pop(); // Removes and returns 30
topNumber = numberStack.Pop(); // Removes and returns 20
// Peek at the top element
int topElement = numberStack.Peek(); // Returns 10 without removing it
Queue
A Queue is a linear data structure that follows the First-In-First-Out (FIFO) principle. It's like a queue of people waiting for a ticket: the first person in line is the first one to be served.
Key Operations:
Enqueue: Adds an element to the rear of the queue.
Dequeue: Removes and returns the element from the front of the queue.
Peek: Returns the element at the front of the queue without removing it.
IsEmpty: Checks if the queue is empty.
Example:
Queue<string> taskQueue = new Queue<string>();
// Enqueue elements into the queue
taskQueue.Enqueue("Task 1");
taskQueue.Enqueue("Task 2");
taskQueue.Enqueue("Task 3");
// Dequeue elements from the queue
string firstTask = taskQueue.Dequeue(); // Removes and returns "Task 1"
firstTask = taskQueue.Dequeue(); // Removes and returns "Task 2"
Real-world Applications:
Stack:
Undo/Redo functionality in text editors
Function call stack in programming languages
Backtracking algorithms
Queue:
Print queue in operating systems
Task scheduling in computer systems
Breadth-first search algorithm
By understanding these fundamental data structures, you can effectively solve a variety of problems.
#CSharp #GenericCollections #Stack #Queue #LIFO #FIFO #Programming #Code #Developer #Tutorial #LearnToCode #CodingTutorial #CSharpTutorial #DataStructures #Algorithms #SoftwareDevelopment #Technology