Site icon DataFlair

Implementation of Queue using Array in DSA Java

Program 1

package dataflair;
import java.util.Scanner;
public class MyQueue 
{
    private int rear = -1;
    private int front = 0;
    private final int MAXSIZE = 10;
    private int queue[] = new int[MAXSIZE];
    Scanner scan = new Scanner(System.in);
    int n;

    public void insert() 
{
        if (rear == MAXSIZE - 1)
            System.out.println("Queue is overflow");
        else {
            System.out.println("Enter an element for insert");
            n = scan.nextInt();
            rear++;
            queue[rear] = n;
        }
    }

    public void delete() 
    {
        if (front > rear)
            System.out.println("Queue is empty");
        else 
        {
            n = queue[front];
            System.out.println("Deleted element is: " + n);
            front++;
        }
    }

    public void display() {
        if (front > rear)
            System.out.println("Queue is empty");
        else {
            System.out.println("\n--- Elements of Queue ---\n");
            for (int i = rear; i >= front; i--)
                System.out.print(queue[i] + " ");
        }
    }
}

Program 2

package dataflair;

import java.util.Scanner;

public class TestQueue 
{

    public static void main(String[] args) 
    {
        

        int choice = 0;
        Scanner scan = new Scanner(System.in);
        MyQueue M = new MyQueue();

        do 
        {
            
            System.out.println("\n------------------QUEUE MENU------------------");
            System.out.println("1. Insert");
            System.out.println("2. Delete");
            System.out.println("3. Display");
            System.out.println("4. Exit");
            System.out.println("\n---------------------------------------------");
            System.out.println("Enter your choice:");
            choice = scan.nextInt();

            switch (choice) 
            {
                case 1: 
                    M.insert();
                    break;
                case 2: 
                    M.delete();
                    break;
                case 3: 
                    M.display();
                    break;
                case 4:
                    break;
                default: 
                    System.out.println("Invalid choice");
            }
        } while (choice != 4);
    }
}

 

Exit mobile version