What are the uses of stack and queue in C# and how to implements them in the C# program?

Asked 26-Aug-2021
Viewed 2386 times

0

What are the uses of stack and queue in C# and how to implements them in the C# program?


1 Answer


0

In C#, Stack and Queue is a class that is used for storing data. Stack is stored data in LIFO (Last in first out) order and Queue is store data in FIFO (First in first out) order.
Stack
using System;

using System.Collections;
public class Program
{
 public static void Main()
 {
  Stack stack=new Stack();
  stack.Push(45);
  stack.Push(12);
  stack.Push(125);
  stack.Push(102);
  foreach(var item in stack)
   Console.WriteLine(item);
 }
}
Output
102

125
12
45
 In this example, we can see print the last value at the first and first value at last in descending order. This is print the last value as a first value and the second-last value as a second value.

Queue
using System;

using System.Collections;
public class Program
{
 public static void Main()
 {
  Queue queue=new Queue();
  queue.Enqueue(45);
  queue.Enqueue(12);
  queue.Enqueue(125);
  queue.Enqueue(102);
  foreach(var item in queue)
   Console.WriteLine(item);
 }
}
Output
45

12
125
102
 In this example, we can see that all value is store in ascending order. The queue is worked on FIFO (first in first out).