WikiGalaxy

Personalize

Queue Enqueue Operations

Introduction to Enqueue:

The enqueue operation adds an element to the rear of the queue. It follows the First-In-First-Out (FIFO) principle, where the first element added is the first to be removed.


    // Queue Enqueue Operation Example
    public class Queue {
      private int front, rear, capacity;
      private int queue[];

      Queue(int c) {
        front = rear = 0;
        capacity = c;
        queue = new int[capacity];
      }

      void enqueue(int data) {
        if (capacity == rear) {
          System.out.println("Queue is full");
          return;
        } else {
          queue[rear] = data;
          rear++;
        }
      }

      void display() {
        if (front == rear) {
          System.out.println("Queue is empty");
          return;
        }
        for (int i = front; i < rear; i++) {
          System.out.print(queue[i] + " ");
        }
        System.out.println();
      }
    }
    

Example 1: Adding Elements

When you enqueue elements 10, 20, and 30, they are added to the queue in the order they are received. The queue becomes [10, 20, 30].


    Queue q = new Queue(5);
    q.enqueue(10);
    q.enqueue(20);
    q.enqueue(30);
    q.display(); // Output: 10 20 30
    

Example 2: Queue Overflow

Attempting to enqueue more elements than the queue can hold results in a "Queue is full" message.


    q.enqueue(40);
    q.enqueue(50);
    q.enqueue(60); // Output: Queue is full
    

Example 3: Circular Queue Concept

In a circular queue, once the rear reaches the end, it wraps around to the beginning if there is space.


    // Assuming a circular queue implementation
    q.enqueue(70);
    q.dequeue();
    q.enqueue(80); // Rear wraps around if space is available
    q.display(); // Output: 20 30 70 80
    

Example 4: Enqueue in a Dynamic Queue

A dynamic queue can grow as needed, avoiding overflow.


    // Assuming a dynamic queue implementation
    DynamicQueue dq = new DynamicQueue();
    dq.enqueue(90);
    dq.enqueue(100);
    dq.enqueue(110);
    dq.display(); // Output: 90 100 110
    

Example 5: Enqueue with Priority

In a priority queue, elements are enqueued based on priority rather than order of arrival.


    PriorityQueue pq = new PriorityQueue();
    pq.enqueue(15, 2); // Element 15 with priority 2
    pq.enqueue(25, 1); // Element 25 with priority 1
    pq.display(); // Output: 25 15 (25 has higher priority)
    
logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025