Code in Java
Create a queue class to store integers and implement following methods:
1) void enqueue(int num): This method will add an integer to the queue (end of the queue).
2) int dequeue(): This method will return the first item in the queue (First In First Out).
3) void display(): This method will display all items in the queue (First item will be displayed first).
4) Boolean isEmpty(): This method will check the queue and if it is empty, this will return true, otherwise false.
class Queue {
//front points to front of Queue
//rear points to rear of Queue
//size is the length of Queue
//array is to store the values
//capacity is the length of the array
int front, rear, size;
int capacity;
int array[];
public Queue(int capacity)
{
this.capacity = capacity;
front = this.size = 0;
rear = capacity - 1;
array = new int[this.capacity];
}
// Queue is empty when size is 0
boolean isEmpty(Queue queue)
{
return (queue.size == 0);
}
//enqueue method to add an num to the queue.
//This changes rear and size
void enqueue(int num)
{
//rear=(rear+1)%capacity
//mod by capacity is to keep rear in range of array length
this.rear = (this.rear + 1) % this.capacity;
//Storing the val in array
this.array[this.rear] = num;
//Queue is increased by 1
this.size = this.size + 1;
}
//dequeue method to remove an num from queue.
//This changes front and size
int dequeue()
{
//If queue is empty
//Case of Underflow
if (isEmpty(this))
return Integer.MIN_VALUE;
int num = this.array[this.front];
//front=(front+1)%capacity
//mod by capacity is to keep fornt in range of array length
this.front = (this.front + 1) % this.capacity;
//Queue is decreased by 1
this.size = this.size - 1;
return num;
}
void display()
{
for(int i=this.front;i < this.front+this.size;i++)
{
System.out.print(this.array[i]+" ");
}
}
}
//Driver class
public class Test {
public static void main(String[] args)
{
Queue queue = new Queue(100);
queue.enqueue(100);
queue.enqueue(150);
queue.enqueue(200);
queue.enqueue(400);
System.out.println("Queue is (before deque) ");
queue.display();
System.out.println();
System.out.println(queue.dequeue()+" dequeued from queue\n");
System.out.println("Queue is (after deque) ");
queue.display();
System.out.println();
System.out.println(queue.dequeue()+" dequeued from queue\n");
System.out.println("Queue is (after deque) ");
queue.display();
}
}
Output Screenshot:
(Note: Please refer to the screenshot of the code to understand the indentation of the code.)
Code Screenshots:
Queue and its constructor:
isEmpty() and enqueue():
dequeue() and display():
main():
Get Answers For Free
Most questions answered within 1 hours.