This is a premium alert message you can set from Layout! Get Now!

C# Stack & Queue

0

C# Stack & Queue


C# Stack: A Key Data Structure in C#

In computer science, a stack is a data structure that operates on a Last-In-First-Out (LIFO) principle. This means that the last item added to the stack is the first one to be removed. C# provides a built-in stack data structure called "Stack" that allows developers to easily implement a LIFO data structure in their applications.

Let's understand with an example, Suppose I need a "data structure" where I can place one item on top of another. When I need an item, I get the item first which I put at the end. Let me give you an example. When we arrange books, we put one on top of the other. This arrangement is called a stack. Now if I want to take a book, I will take the book that is above all. It means I will out the book first which I put at the end. You can call it "Last in, First out". C# has a built-in stack data structure.

C# Stack


Why Use a Stack in C#?

A stack is a useful data structure in many programming scenarios. Some common uses of a stack include:
  1. Undo/Redo operations: A stack can be used to keep track of the history of changes made to a document or application.
  2. Function calls: A stack can be used to store the sequence of function calls made in a program.
  3. Expression evaluation: A stack can be used to evaluate arithmetic expressions in a program.

Namespace of Stack
The stack can be generic and non-generic. 

If the type is non-generic then the namespace is
using System.Collections;

Syntax of declaration of non-generic type Stack is
Stack stackName = new Stack();

If the type is generic then the namespace is
using System.Collections.Generic;

Syntax of  declaration of generic type Stack is
Stack<int> stackName = new Stack<int>();

Key Methods of the C# Stack Class

The C# Stack class provides several methods for working with a stack data structure, including:
  1. Push: Adds an item to the top of the stack.
  2. Pop: Removes the item from the top of the stack and returns it.
  3. Peek: Returns the item at the top of the stack without removing it.
  4. Count: Returns the number of items in the stack.
  5. Clear: Removes all items from the stack.
Add items to the Stack
stackName.Push(10); // First In
stackName.Push(20); 
stackName.Push(30); 
stackName.Push(40); // Last In

Iterate over the Stack
foreach (var item in stackName) 
     Console.Write(item + " "); 
}

Output:
40 30 20 10

Remove an item from the Stack
stackName.Pop();
40 will be deleted. Because 40 was the last item.

Example Use of the C# Stack Class

Here is an example of how the C# Stack class can be used to implement a simple arithmetic expression evaluator:
Stack<string> stack = new Stack<string>();

foreach (string token in expression)
{
    if (token is a number)
    {
        stack.Push(token);
    }
    else if (token is an operator)
    {
        int right = int.Parse(stack.Pop());
        int left = int.Parse(stack.Pop());
        int result = Evaluate(left, right, token);
        stack.Push(result.ToString());
    }
}

return int.Parse(stack.Pop());

In this example, the expression is broken down into individual tokens and pushed onto the stack. When an operator is encountered, the two most recent numbers are popped off the stack, evaluated using the operator, and the result is pushed back onto the stack. The final result is returned when the stack is empty.

Conclusion of Stack

The C# Stack class provides a convenient and efficient way to implement a Last-In-First-Out data structure in C#. With its key methods and ability to store any type of object, the C# Stack class is a versatile tool for solving a wide range of programming problems.

C# Queue: An Essential Data Structure in C#

In computer science, a queue is a data structure that operates on a First-In-First-Out (FIFO) principle. This means that the first item added to the queue is the first one to be removed. C# provides a built-in queue data structure called "Queue" that allows developers to easily implement a FIFO data structure in their applications.

Let's understand with an example, When we withdraw money at the bank, we stand in line. Whoever comes first will be able to withdraw money first. That way when we go to buy a ticket he stands in line and whoever comes first will get the ticket first. That's why "First In, First Out" is happening here. Such a data structure is Queue. The data that enters first will be exited first.

C# Queue


Why Use a Queue in C#?

A queue is a useful data structure in many programming scenarios. Some common uses of a queue include:
  1. Job scheduling: A queue can be used to keep track of tasks that need to be performed, ensuring that tasks are processed in the order they were added to the queue.
  2. Event handling: A queue can be used to store events that need to be processed, ensuring that events are handled in the order they were received.
  3. Breadth-first search algorithms: A queue can be used to implement breadth-first search algorithms in graph theory.

Key Methods of the C# Queue Class

The C# Queue class provides several methods for working with a queue data structure, including:
  1. Enqueue: Adds an item to the end of the queue.
  2. Dequeue: Removes the item from the front of the queue and returns it.
  3. Peek: Returns the item at the front of the queue without removing it.
  4. Count: Returns the number of items in the queue.
  5. Clear: Removes all items from the queue.
Namespace of Queue
The queue also can be generic and non-generic. 

If the type is non-generic then the namespace is
using System.Collections;

Syntax of declaration of non-generic type Queue is
Queue qName=new Queue();

If the type is generic then the namespace is
using System.Collections.Generic;

Syntax of declaration of generic type Queue is
Queue <int> qName=new Queue <int>();

Add items to the Queue
qName.Enqueue(10); //First In
qName.Enqueue(20); 
qName.Enqueue(30); 
qName.Enqueue(40); //Last In

Iterate over the Queue
foreach (var item in qName)
{
    Console.Write(item + " ");
}
output:
10 20 30 40

Remove an item from the Queue
qName.Dequeue();

10 will be deleted. Because 10 was the first item.

Example Use of the C# Queue ClassExample Use of the C# Queue Class

Here is an example of how the C# Queue class can be used to implement a simple job scheduler:
Queue<Job> queue = new Queue<Job>();

foreach (Job job in jobs)
{
    queue.Enqueue(job);
}

while (queue.Count > 0)
{
    Job nextJob = queue.Dequeue();
    nextJob.Run();
}

In this example, the jobs are added to the queue in the order they were received. The scheduler processes the jobs by dequeuing them one at a time and running them. The queue is emptied when all jobs have been processed.

Conclusion of Queue

The C# Queue class provides a convenient and efficient way to implement a First-In-First-Out data structure in C#. With its key methods and ability to store any type of object, the C# Queue class is a versatile tool for solving a wide range of programming problems. Whether you are scheduling jobs, handling events, or implementing graph algorithms, the C# Queue class is an essential tool for any C# developer.


Tags

Post a Comment

0 Comments
Post a Comment

#buttons=(Ok, Go it!) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Ok, Go it!
To Top