Implement Queue Using Arrays

How to Implement Queue Using Arrays?

 

To implement a queue using arrays ,you can follow these steps:

  1. Create an array to store the elements of the queue.
  2. Create variables to keep track of the front and rear of the queue.
  3. Initialize the front variable to 0 and the rear variable to -1.
  4. To add an element to the queue, increment the rear variable and add the element to the position indicated by the rear variable.
  5. To remove an element from the queue, increment the front variable and return the element at the position indicated by the front variable.
  6. Implement methods to check if the queue is empty or full, as well as to get the size of the queue.

Let us understand the implementation of queue using arrays in Java with the help of an example:

public class QueueUsingArrays {
   private int[] arr;
   private int front;
   private int rear;
   private int size;

   // Creating Constructor
   public QueueUsingArrays(int capacity) {
       arr = new int[capacity];
       front = 0;
       rear = -1;
       size = 0;
   }
   
   // Adds the element in the queue
   public void enqueue(int item) {
       if (isFull()) {
           System.out.println("Queue is full");
           return;
       }
       rear++;
       arr[rear] = item;
       size++;
   }
   
   // Removes the element from the queue
   public int dequeue() {
       if (isEmpty()) {
           System.out.println("Queue is empty");
           return -1;
       }
       int item = arr[front];
       front++;
       size--;
       return item;
   }
   
   // Returns the front element in the queue
   public int peek() {
       if (isEmpty()) {
           System.out.println("Queue is empty");
           return -1;
       }
       return arr[front];
   }
   
   // Returns a boolean value if queue is empty
   public boolean isEmpty() {
       return size == 0;
   }
   
   // Returns a boolean value if queue is full
   public boolean isFull() {
       return rear == arr.length - 1;
   }
   
   // Returns size of the queue
   public int size() {
       return size;
   }
 
 public static void main(String[] args)   
  {  
    QueueUsingArrays queue = new QueueUsingArrays(5);  
    queue.enqueue(7);  
    queue.enqueue(9);  
    System.out.println("Peek element: "+queue.peek());
    System.out.println("Deleted element: " + queue.dequeue());  
    System.out.println("Deleted element: " + queue.dequeue());  
    queue.enqueue(11);      
    System.out.println("Deleted element: " + queue.dequeue());      
  }  
}


Output 

Peek element: 7
Deleted element: 7
Deleted element: 9
Deleted element: 11

Comments

Popular posts from this blog

Two Sum II - Input Array Is Sorted

Comparable Vs. Comparator in Java

Increasing Triplet Subsequence