C# program to implement linear queue using array

In this C# program, we will learn about linear queue implementation. Here, we are implementing linear queue using array.
Submitted by IncludeHelp, on November 21, 2017 [Last updated : March 27, 2023]

Linear Queue

Linear Queue follows FIFO (First In First Out) property, it means first inserted elements, deleted first. In linear queue there are two pointers are used:

  1. FRONT : It points the location from where we can delete an item from linear queue.
  2. REAR : It points the location from where we can insert element into linear queue.

Linear queue implementation using array in C#

using System;

namespace ConsoleApplication1
{
    class LinearQueue
    {
        private int []ele;
        private int front;
        private int rear;
        private int max;

        public LinearQueue(int size)
        {
            ele = new int[size];
            front  = 0 ;
            rear   = -1;
            max = size;
        }

        public void insert(int item)
        {
            if (rear == max-1)
            {
                Console.WriteLine("Queue Overflow");
                return;
            }
            else
            {
                ele[++rear] = item;
            }
        }

        public int delete()
        { 
            if(front == rear + 1)
            {
                Console.WriteLine("Queue is Empty");
                return -1;
            }
            else
            {
                Console.WriteLine("deleted element is: " + ele[front]);
                return ele[front++];
            }
        }

        public void printQueue()
        {
            if (front == rear + 1)
            {
                Console.WriteLine("Queue is Empty");
                return;
            }
            else
            {
                for (int i = front; i <= rear; i++)
                {
                    Console.WriteLine("Item[" + (i + 1) + "]: " + ele[i]);
                }
            }
        }
    }

    class Program
    {
        static void Main()
        {
            LinearQueue Q = new LinearQueue(5);

            Q.insert(10);
            Q.insert(20);
            Q.insert(30);
            Q.insert(40);
            Q.insert(50);

            Console.WriteLine("Items are : ");
            Q.printQueue();
            
            Q.delete();
            Q.delete();

            Console.WriteLine("Items are : ");
            Q.printQueue();
        }
    }
}

Output

Items are :
Item[1]: 10
Item[2]: 20
Item[3]: 30
Item[4]: 40
Item[5]: 50
deleted element is: 10
deleted element is: 20
Items are :
Item[3]: 30
Item[4]: 40
Item[5]: 50

Note: In Linear queue we cannot insert element at deleted location because front is moved ahead after deletion, to remove this problem we can use circular queue.

C# Data Structure Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.