March 05, 2024

Java Problems Solutions: Implement a Queue in Java


public class MyQueue {
    private int maxSize; // Maximum size of the queue
    private String[] queueArray; // Array to hold the queue elements
    private int front; // Index of the front element in the queue
    private int rear; // Index of the rear element in the queue
    private int currentSize; // Current size of the queue

    public static void main(String[] args) {// Test the queue
        MyQueue queue = new MyQueue(3); // Set max size to 3
        queue.enqueue("A");
        queue.enqueue("B");
        queue.enqueue("C");
        queue.enqueue("D"); // Attempt to enqueue into a full queue
        
        System.out.println("Is the queue full? " + queue.isFull());
        
        System.out.println("Front element: " + queue.peek());
        System.out.println("Dequeue: " + queue.dequeue());
        System.out.println("Front element after dequeue: " + queue.peek());
        
        queue.dequeue();queue.dequeue();
        System.out.println("Is the queue empty? " + queue.isEmpty());        
        queue.dequeue(); // Attempt to dequeue from an empty queue
    }

    public MyQueue(int size) {// Constructor to initialize the queue with a specified size
        maxSize = size;
        queueArray = new String[maxSize];
        front = 0; // Initialize front as 0
        rear = -1; // Initialize rear as -1
        currentSize = 0; // Initialize currentSize as 0
    }

    public void enqueue(String value) {// Method to enqueue an element into the queue
        if (!isFull()) {
            rear = (rear + 1) % maxSize;
            queueArray[rear] = value;
            currentSize++;
        } else {
            System.out.println("Cannot enqueue. Queue is full.");
        }
    }

    public String dequeue() {// Method to dequeue an element from the queue
        if (!isEmpty()) {
            String removedItem = queueArray[front];
            front = (front + 1) % maxSize;
            currentSize--;
            return removedItem;
        } else {
            System.out.println("Cannot dequeue. Queue is empty.");
            return null;
        }
    }

    public String peek() {// Method to get the front element of the queue without removing it
        if (!isEmpty()) {
            return queueArray[front];
        } else {
            System.out.println("Queue is empty.");
            return null;
        }
    }

    public boolean isEmpty() {// Method to check if the queue is empty
        return currentSize == 0;
    }

    public boolean isFull() {// Method to check if the queue is full
        return currentSize == maxSize;
    }
}

Want 1 to 1 personalized Java training? Email me at isingh30 AT gmail please. View my following video

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.