Circular Queue implementation


import java.util.Arrays;

/**
 * Key points : 
 * 1. Max capecity can be size-1. As 1 space in queue will alway be empty
 * 2. Next index = (currentIndex+1)%size
 * 3. Empty condition : front == rear 
 * 4. Full condition : (front+1)%size == rear
 */
class CircularQueue {
    // for dequeue operation
    private int front;
    // for enqueue operation 
    private int rear;
    private int capacity;
    private int[] array;
    private static final int DEFAULT_CAPACITY = 6; // we can insert 5 elements
    
    public CircularQueue() {
        this(DEFAULT_CAPACITY);
    }
    
    public CircularQueue(int capacity) {
        this.front = this.rear = 0;
        this.capacity = capacity < DEFAULT_CAPACITY ? DEFAULT_CAPACITY : capacity;
        array = new int[capacity];
    }
    
    public void enqueue(int data) {
        if(isFull()) {
            System.out.println(data + " is not inserted. Queue is full");
        } else {
            rear = (rear + 1) % capacity;
            array[rear] = data;
        }
    }
    
    public int dequeue() {
        if(empty()) {
            System.out.println("Queue is empty.");
            return -1;
        }
        front = (front + 1) % capacity;
        return array[front];
    }
    
    public boolean isFull() {
       return (rear + 1) % capacity == front;
    }
    
    public boolean empty() {
       return front == rear;
    }
    
    public void display() {
        if(empty()) {
            return;
        }
        int i = (front + 1) % capacity;
        do {
            System.out.print(array[i] + " ");
            i = (i + 1) % capacity;
        } while(i != (rear + 1) % capacity);
    }
    
    public static void main (String[] args) {
        int[] array = new int[] {1, 3, 5, 7, 9};
        CircularQueue queue = new CircularQueue();
        Arrays.stream(array).forEach(d -> queue.enqueue(d));
        
        // Display
        System.out.println("Display queue");
        queue.display();
        
        // Overflow
        System.out.println("\nInsert 10");
        queue.enqueue(10);
        
        // Dequeue
        System.out.println("Deleting all from queue");
        for(int i = 0; i < 5; i++) {
            queue.dequeue();
        }
        
        // Underflow
        System.out.println("Try deleting again when no elements in queue");
        queue.dequeue();
    }
}

Output
Display queue
1 3 5 7 9 
Insert 10
10 is not inserted. Queue is full
Deleting all from queue
Try deleting again when no elements in queue
Queue is empty.

Comments

Popular posts from this blog

SQL basic interview question

gsutil Vs Storage Transfer Service Vs Transfer Appliance