Java program to implement the queue data structure
Here's an example Java program that implements the Queue data structure using an array:
rrefe to:theitroad.compublic class Queue { private int front, rear, size; private int capacity; private int[] array; public Queue(int capacity) { this.capacity = capacity; front = this.size = 0; rear = capacity - 1; array = new int[this.capacity]; } public boolean isFull(Queue queue) { return (queue.size == queue.capacity); } public boolean isEmpty(Queue queue) { return (queue.size == 0); } public void enqueue(int item) { if (isFull(this)) return; rear = (rear + 1) % capacity; array[rear] = item; size++; } public int dequeue() { if (isEmpty(this)) return Integer.MIN_VALUE; int item = array[front]; front = (front + 1) % capacity; size--; return item; } public int front() { if (isEmpty(this)) return Integer.MIN_VALUE; return array[front]; } public int rear() { if (isEmpty(this)) return Integer.MIN_VALUE; return array[rear]; } public static void main(String[] args) { Queue queue = new Queue(5); queue.enqueue(10); queue.enqueue(20); queue.enqueue(30); queue.enqueue(40); queue.enqueue(50); System.out.println("Front element is: " + queue.front()); System.out.println("Elements removed from the queue:"); System.out.println(queue.dequeue()); System.out.println(queue.dequeue()); System.out.println("Queue after elements are removed:"); System.out.println("Front element is: " + queue.front()); System.out.println("Rear element is: " + queue.rear()); } }
This program implements a Queue data structure using an array of integers. The Queue has a fixed capacity, which is set when the Queue is created. The Queue has four methods: enqueue()
, dequeue()
, front()
, and rear()
. The enqueue()
method adds an item to the end of the Queue, the dequeue()
method removes the first item from the Queue, and the front()
and rear()
methods return the first and last items in the Queue, respectively.
The isFull()
and isEmpty()
methods are helper methods that check whether the Queue is full or empty, respectively.
The main()
method creates a Queue with a capacity of 5 and adds five elements to the Queue using the enqueue()
method. It then prints the front element of the Queue using the front()
method, removes the first two elements from the Queue using the dequeue()
method, and prints the front and rear elements of the Queue again.