Queue implementation in c#

Jack Herer 105 Reputation points
2023-04-20T17:34:13.37+00:00

I'm just posting how to implement queue in c#... I hope someone finds it helpfull

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,647 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,648 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Jack Herer 105 Reputation points
    2023-04-20T17:35:01.5966667+00:00
    Console.WriteLine("Hello, World!");
    Queue queue = new(6);
    queue.Enqueue(4);
    queue.Enqueue(2);
    queue.Enqueue(0);
    queue.Enqueue(420);
    queue.Enqueue(69);
    queue.Enqueue(42069);
    queue.GetAllItems();
    Console.WriteLine($"Item deleted: {queue.Dequeue()}"); 
    queue.GetAllItems();
    Console.WriteLine();
    Console.WriteLine($"Item peeked: {queue.Peek()}");
    
    internal class Queue
    {
        private int front;
        private int rear;
        private int[] queue;
    
        public Queue(int size)
        {
            front = 0;
            rear = -1;
            queue = new int[size];
        }
    
        // if queue isn't full, adds new item to front of the queue and sets front value to the new item
        public void Enqueue(int item)
        {
            if (rear == queue.Length - 1)
            {
                throw new StackOverflowException("Queue is full");
            }
            queue[++rear] = item;
        }
    
        // if the queue isn't empty, sets first item as upcomming one
        public int Dequeue()
        {
            if (front > rear)
            {
                throw new Exception("Queue is empty");
            }
            int item = queue[front];
            front++;
            return item;
        }
    
        // if the queue isn't empty, returns first value
        public int Peek()
        {
            if (front > rear)
            {
                throw new Exception("Queue is empty");
            }
            return queue[front];
        }
    
        // writes all items starting from front to rear
        public void GetAllItems()
        {
            Console.WriteLine("Items of queue are:");
            for (int i = front; i <= rear; i++)
            {
                Console.WriteLine(queue[i]);
            }
        }
    }
    
    0 comments No comments