How to double the size of a queue in java - java

I've been trying to double the size of my queue and I have tried several different methods, this one has given me the closest result to what I am trying to get, however, it copies all the values already in the queue into the newly created spaces instead of leaving them empty for me to add more objects.
I have two classes, and the only part I need to change is the enqueue method.
The last line should print 50 40 30 20 60 70 instead.
public class Queue{
private int QUEUE_SIZE = 5;
private Object[] items;
private int front, back, count;
public Queue() {
items = new Object[QUEUE_SIZE];
front = 0;
back = QUEUE_SIZE -1;
count =0;
}
public boolean isEmpty(){
return count ==0;
}
public boolean isFull(){
return count == QUEUE_SIZE;
}
public void enqueue(Object newItem){
if (!isFull()){
back = (back+1) % QUEUE_SIZE;
items[back] = newItem;
count++;
return;
} else
System.out.println("Queue is full. Doubling the size.");
count = (QUEUE_SIZE*2);
System.out.println("New max size is: " + QUEUE_SIZE);
}
public Object dequeue(){
if (!isEmpty()){
Object queueFront = items[front];
front = (front+1) % QUEUE_SIZE;
count--;
return queueFront;
}else
System.out.println("Trying to dequeue from empty queue");
return null;
}
public void dequeueAll(){
items = new Object[QUEUE_SIZE];
front = 0;
back = QUEUE_SIZE -1;
count =0;
}
public Object peek(){
if (!isEmpty()) {
return items[front];
}
else
System.out.println("Trying to peek with empty queue");
return null;
}
public int size(){
return count;
}
}
import java.util.Stack;
public class Runner {
public static void main(String[] args) {
Queue q = new Queue();
createQueue(q);
System.out.println("My queue is as follows: ");
printQueue(q);
System.out.println("I am going to dequque one element.");
q.dequeue();
System.out.println("My queue is as follows: ");
printQueue(q);
System.out.println("I am going to reverse my queue: ");
reverseQueue(q);
System.out.println("My queue is as follows: ");
printQueue(q);
System.out.println("I am going to enqueue 60.");
q.enqueue(60);
System.out.println("My queue is as follows: ");
printQueue(q);
System.out.println("I am going to enqueue 70.");
q.enqueue(70);
System.out.println("My queue is as follows: ");
printQueue(q);
}
public static Queue createQueue(Queue q){
q.enqueue(10);
q.enqueue(20);
q.enqueue(30);
q.enqueue(40);
q.enqueue(50);
return q;
}
public static void printQueue(Queue q){
int s = q.size();
for(int i=0; i<s; i++){
int temp = (int)q.dequeue();
q.enqueue(temp);
System.out.print(temp+ " ");
}
System.out.println();
}
public static void reverseQueue(Queue q){
Stack s = new Stack();
while(!q.isEmpty()){
s.push(q.dequeue());
}while(!s.isEmpty()){
q.enqueue(s.pop());
}
}
}

The else block in enqueue(Object newItem) does not insert new Object so it should be like this :
public void enqueue(Object newItem) {
if (!isFull()) {
back = (back + 1) % QUEUE_SIZE;
items[back] = newItem;
count++;
return;
}
else {
System.out.println("Queue is full. Doubling the size.");
QUEUE_SIZE = (QUEUE_SIZE * 2); // double queue size not count
System.out.println("New max size is: " + QUEUE_SIZE);
Object[] temp = new Object[QUEUE_SIZE]; // temp array
System.arraycopy(items, front, temp, front, items.length - front); // copy the elements from front index to items.length-front
if (front != 0) {
System.arraycopy(items, 0, temp, items.length, front); // copy the elements in the range items[0] to items[back] into the new array
}
items = temp; // set items to temp array
back = front + count;
items[back] = newItem; // set new item
count++; // increment count
}
}

It is about printQueue() method, after the count = (QUEUE_SIZE*2); line of enqueue() method the size of items array actually didn't expand. It is still 5 in any case, count = (QUEUE_SIZE*2); provide that isFull() method returns false.
If you debug printQueue() method, you will see that int s = 10 but items array still [30, 20, 60, 50, 40].

After Queue becomes full, You are not enqueuing the items. So the item is not inserted into the queue after becomes full.Have modified the code.
package org.sunil.addressbook.dao;
import java.util.Stack;
class Queue{
private int QUEUE_SIZE = 5;
private Object[] items;
private int front, back, count;
public Queue() {
items = new Object[QUEUE_SIZE];
front = 0;
back = QUEUE_SIZE -1;
count =0;
}
public boolean isEmpty(){
return count ==0;
}
public boolean isFull(){
return count == QUEUE_SIZE;
}
public void enqueue(Object newItem){
if (!isFull()){
back = (back+1) % QUEUE_SIZE;
// System.out.println("back output is "+back);
items[back] = newItem;
count++;
} else{
System.out.println("Queue is full. Doubling the size.");
back=QUEUE_SIZE-1;
QUEUE_SIZE = (QUEUE_SIZE*2);
Object[] temp = new Object[QUEUE_SIZE];
int j=0;
for (int i = front; i < items.length; i++){
temp[j] = items[i];
j++;
}
for (int i = 0; i < front; i++){
temp[j] = items[i];
j++;
}
items = temp;
front=0;
back = (back+1) % QUEUE_SIZE;
items[back] = newItem;
count++;
}
}
public Object dequeue(){
if (!isEmpty()){
Object queueFront = items[front];
front = (front+1) % QUEUE_SIZE;
count--;
return queueFront;
}else
System.out.println("Trying to dequeue from empty queue");
return null;
}
public void dequeueAll(){
items = new Object[QUEUE_SIZE];
front = 0;
back = QUEUE_SIZE -1;
count =0;
}
public Object peek(){
if (!isEmpty()) {
return items[front];
}
else
System.out.println("Trying to peek with empty queue");
return null;
}
public int size(){
return count;
}
}
public class Runner {
public static void main(String[] args) {
Queue q = new Queue();
createQueue(q);
System.out.println("My queue is as follows: ");
printQueue(q);
System.out.println("I am going to dequque one element.");
q.dequeue();
System.out.println("My queue is as follows: ");
printQueue(q);
System.out.println("I am going to reverse my queue: ");
reverseQueue(q);
System.out.println("My queue is as follows: ");
printQueue(q);
System.out.println("I am going to enqueue 60.");
q.enqueue(60);
System.out.println("My queue is as follows: ");
printQueue(q);
System.out.println("I am going to enqueue 70.");
q.enqueue(70);
System.out.println("My queue is as follows: ");
printQueue(q);
}
public static Queue createQueue(Queue q){
q.enqueue(10);
q.enqueue(20);
q.enqueue(30);
q.enqueue(40);
q.enqueue(50);
return q;
}
public static void printQueue(Queue q){
int s = q.size();
for(int i=0; i<s; i++){
int temp = (Integer)q.dequeue();
q.enqueue(temp);
System.out.print(temp+ " ");
}
System.out.println();
}
public static void reverseQueue(Queue q){
Stack s = new Stack();
while(!q.isEmpty()){
s.push(q.dequeue());
}while(!s.isEmpty()){
q.enqueue(s.pop());
}
}
}

Related

displaying circular queue in java

I have the following code where I have implemented a circular array. The problem comes when I try to display it. The display method works well until the array gets full and last goes back to 0. Therefore last and first are both 0 and the for loop doesn't execute.
public class PassengerQueue
{
private Passenger[] queueArray = new Passenger[TrainStation.WAITING_ROOM_CAPACITY];
private int first = 0;
private int last = 0;
private int maxStayInQueue = 0; //number of seconds that the passenger who stayed longest in the queue
private int maxLength = 0; //the maximum legth that was reached by the queue
private int currentSize = 0;
public void add(Passenger next)
{
//if the queue is not full - check for the circular queue
if (isFull()){
System.out.println("The queue is full");
}
else
{
queueArray[last] = next;
last = (last + 1) % queueArray.length;
currentSize++;
maxLength++;
}
}
public Passenger remove()
{
Passenger removedPassenger = null;
//if the queue array is not empty
//remove passenger
if (isEmpty())
{
System.out.println("The queue is empty");
}
else
{
removedPassenger = queueArray[first];
queueArray[first] = null;
first = (first + 1) % queueArray.length;
currentSize--;
}
return removedPassenger;
}
public Boolean isEmpty()
{
return (currentSize == 0);
}
public Boolean isFull()
{
return (currentSize == queueArray.length);
}
public void display()
{
if (isEmpty())
{
System.out.println("The queue is empty");
}
else
{
for(int i = first; i < last; i++)
{
queueArray[i].display();
}
}
}
Any help would be appreciated! Thank You
You can change the loop so it iterates from 0 to size. This also fixes the problem where last is less than first because items have been removed.
for(int i = 0; i < currentSize; i++)
{
queueArray[(first + i) % queueArray.length].display();
}
Just use the properties on the array itself to display:
public void display()
{
if (isEmpty())
{
System.out.println("The queue is empty");
}
else
{
for(int i = 0; i < queueArray.length; i++)
{
queueArray[i].display();
}
}
}

Creating an Array of Queues

I have to make a program in Java that includes an array of queues created from my queue class that I have made which is as follows -
class Queue1{ //each line at the supermarket
public Queue1(int s){ //constructor
maxSize = s;
pplLines = new long[maxSize];
front = 0;
rear = -1;
nItems = 0;
}
public void insert(long j){ //put item at rear of queue
if(rear == maxSize - 1) //deal with wraparound
rear = -1;
pplLines[++rear] = j; //increment rear and insert
nItems++; //one more item
}
public long remove(){ //take item from front of queue
long temp = pplLines[front++]; //get value and increment front
if(front == maxSize) //deal with wraparound
front = 0;
nItems--; //one less item
return temp;
}
public long peekFront(){ //peek at front of queue
return pplLines[front];
}
public boolean isEmpty(){ //true if queue is empty
return (nItems == 0);
}
public boolean isFull(){ //true if queue is full
return (nItems == maxSize);
}
public int size(){ //number of items in queue
return nItems;
}
public void display(){ //display contents of queue
for (int i = 0; i < nItems; i++) {
System.out.println(pplLines[(front + i) % maxSize]);
}
}
}//ends queue class
So how can I reference the queue class into an array starting with this
public SuperMarket(int num_clerks, int line_size){
After that I have the array of queues created I need to find the shortest line to insert a customer where I have to input the number of clerks/lines available at the supermarket, how would I go about adding that to my SuperMarket class?
Thanks for the help!
if you do something like
public SuperMarket(int num_clerks, int line_size){
List<Queue1> clerks = new ArrayList<Queue1>();
for(int i; i< num_clerks; i++){
clerks.add(new Queue1(line_size))
}
}

why are my substrings not being added to my queue?

the program I am working on is supposed to have you enter a gender and name of a person ex: "m john"
And then it is supposed to separate the males and females and print out just the name separately.
I have am comparing the first character in the string and then using enqueue to add a substring to either a male queue or a female queue and then I am trying to print each queue by printing the dequeued substring. but I get an error that my queue is empty even though I have added strings in my for loop.
public class GenderSorter
{
public static void main(String[] args)
{
int numElements;
int maleCount = 0;
int femaleCount = 0;
Scanner keyboard = new Scanner(System.in);
System.out.println("How many people are you adding: ");
numElements = keyboard.nextInt();
keyboard.nextLine();
ArrayBndQueue male = new ArrayBndQueue<>();
ArrayBndQueue female = new ArrayBndQueue<>();
for(int index = 1; index <= numElements; index++)
{
/*
System.out.println("Enter a gender and name (ex: f jenny)");
String name = keyboard.nextLine();
System.out.println(name);
*/
System.out.println("Enter a gender and name (ex: f jenny)");
String name = keyboard.nextLine();
char character = name.charAt(0);
if(character == 'f')
{
female.enqueue(name.substring(2));
femaleCount++;
}
else
{
male.enqueue(name.substring(2));
maleCount++;
}
}
System.out.println("Females: " + "\n");
for(int index2 = 0; index2 <= femaleCount; index2++)
{
System.out.print(female.dequeue());
}
System.out.println("Males: " + "\n");
for(int index3 = 0; index3 <= maleCount; index3++)
{
System.out.print(male.dequeue());
}
}
}
Here is my ArrayBndQueue:
public class ArrayBndQueue<T> implements BoundedQueueInterface<T>
{
protected final int DEFCAP = 100;
protected T[] queue;
protected int numElements = 0;
protected int front = 0;
protected int rear;
public ArrayBndQueue()
{
queue = (T[]) new Object[DEFCAP];
rear = DEFCAP -1;
}
public ArrayBndQueue(int maxSize)
{
queue = (T[]) new Object[maxSize];
rear = maxSize -1;
}
public void enqueue(T element)
{
if(isFull())
{
throw new QueueOverflowException("Enqueue " + "attempted on full queue");
}
else
{
rear = (rear + 1) % queue.length;
queue[rear] = element;
numElements++;
}
}
public boolean isFull()
{
return (numElements == queue.length);
}
public boolean isEmpty()
{
return (numElements == 0);
}
public T dequeue()
{
if(isEmpty())
{
throw new QueueUnderflowException("Dequeue" +
" attempted on empty queue!");
}
else
{
T toReturn = queue[front];
queue[front] = null;
front = (front + 1) % queue.length;
numElements--;
return toReturn;
}
}
}
Perhaps it's not the only problem, but
for(int index2 = 0; index2 <= femaleCount; index2++)
should be
for(int index2 = 0; index2 < femaleCount; index2++)
As it is, the last dequeue would give you the QueueUnderflowException, since you are trying to dequeue n+1 items from a queue that contains only n.
Same problem exists for both male and female loops.

Queue implementation as Array

So I was required to do an implementation of queue in arrays, and I wasn't having any trouble till I saw I was getting a funny output after I dequeue and try to enqueue another value...
For example (output):
Queue: [1] //Enqueue 1
Queue: [1, 2] //Enqueue 2
Queue: [2] //Dequeue
Queue: [2, 2] //Enqueue 3
Queue: [2, 2, 3] //Enqueue 4
Queue: [5, 2, 3, 4] //Now is a total mess...
My code contains queue, dequeque and resize methods everything was working fine and I really don't have any idea at all of how to fix it anymore...
Here's my code with the main if you want to try it. Thanks.
public class MainQueue {
public static void main(String[] args) {
int capacity=5;
Queue<Integer> queue = new Queue<Integer>(capacity);
queue.enqueue(1);
System.out.println("Queue: "+ queue);
queue.enqueue(2);
System.out.println("Queue: "+ queue);
queue.dequeue();
queue.enqueue(3);
System.out.println("Queue: "+ queue);
queue.enqueue(4);
System.out.println("Queue: "+ queue);
queue.enqueue(5);
System.out.println("Queue: "+ queue);
}
}
Class
import java.util.NoSuchElementException;
public class Queue<E> {
private E[] elements;//array in generic
private int front;//first element or front of the queue
private int back;//last element or back of the queue
private int capacity; //capacity of the queue
private int count; //indicates number of elements currently stored in the queue
public Queue(int size)
{
capacity = size;
count = 0;
back = size-1;
front = 0;
elements =(E []) new Object[size]; //queue array empty
}
//Returns true if the queue is empty or false
public boolean isEmpty()
{
return count==0;//means its true
}
//Add elements to the queue
public void enqueue(E item)
{
if(count == capacity)
{
resize(capacity*2);
// System.out.println("Queue is full");
}
back =(back+1) % capacity; //example back=(0+1)%10=1
elements[back]=item;
//elements[0]=0
//item=elements[count];
count++;
}
//Public resize
public void resize(int reSize){
E[] tmp = (E[]) new Object[reSize];
int current = front;
for (int i = 0; i < count; i++)
{
tmp[i] = elements[current];
current = (current + 1) % count;
}
elements = tmp;
front = 0;
back = count-1;
capacity=reSize;
}
//Dequeue method to remove head
public E dequeue()
{
if(isEmpty())
throw new NoSuchElementException("Dequeue: Queue is empty");
else
{
count--;
for(int x = 1; x <= count; x++)
{
elements[x-1] = elements[x];
}
capacity--;
return (E) elements;
}
}
//peek the first element
public E peek()
{
if(isEmpty())
throw new NoSuchElementException("Peek: Queue is empty");
else
return elements[front];
}
//Print queue as string
public String toString()
{
if(isEmpty()) {
throw new NoSuchElementException("Queue is empty");
}
String s = "[";
for(int i = 0; i < count; i++)
{
if(i != 0)
s += ", ";
s = s + elements[i];// [value1,value2,....]
}
s +="]";
return s;
}
public void delete() { //Delete everything
count = 0;
}
}
You are updating the back in the enqueue() method using the current value of back, but you aren't updating it in the dequeu() method at all. That is not going to work correctly. In fact, you should rather calculate back based on count.
Just change:
back = (back + 1) % capacity;
to:
back = count % capacity;
In dequeue you are not updating the back variable that determines the position on which you add new value with enqueue. Furthermore in dequque you could copy nonexistent value on index 0 from index 1 when you have count just of 1. This is a special case that will make out of bounds error if you made a queue with capacity(size) of 1, enqueued something and then dequeued it.

How to code Queue in Java

I'm trying to make a Queue in java.
The problem is that I don't know how to remove(?) a value from the array, the index value which I dequeue.
This is my code.
front() method is the dequeue part. and I used iter_ to set the current index position.
but as you can see, it dequeue's the corret value though the value still remains inside the array:(
public class IntQueue {
private int[] items_;
private int top_;
private int capacity_;
private int iter_;
public IntQueue(int capacity)
{
if(capacity <=0) capacity = 10;
capacity_ = capacity;
top_=0;
count_ = 0;
iter_=0;
items_= new int[capacity_];
}
public void push_back(int value)
{
if(top_>= capacity_)
overflow();
items_[top_++]=value;
count_++;
}
public int front()
{
if(top_<=0)
return 0;
int temp=0;
temp=items_[iter_];
count_--;
iter_++;
return temp;
}
public IntQueue clone()
{
IntQueue result = new IntQueue(capacity_);
for(int i=0 ; i<top_; ++i)
{
result.push_back(items_[i]);
}
/*for(int i=0 ; i<top_ ; ++i)
{
result.items_[i] = items_[i];
}*/
return result;
}
public void log()
{
for(int i=0 ; i <top_; ++i)
{
System.out.print(items_[i]);
if(i<top_ -1)
System.out.print(", ");
}
System.out.println();
}
}
private void overflow()
{
int[] newItem = new int[capacity_*2];
for(int i=0 ; i <top_; ++i)
newItem[i] = items_[i];
items_=newItem;
capacity_ *=2;
}
public static void main(String args[])
{
IntQueue queue = new IntQueue(2);
System.out.println("queue push 3: "); queue.push_back(3);
System.out.println("queue push 2: "); queue.push_back(2);
System.out.println("queue push 1: "); queue.push_back(1);
System.out.print("queue log: "); queue.log();
System.out.println("front " + queue.front());
System.out.println("front " + queue.front());
System.out.print("queue log: "); queue.log();
System.out.println("queue push 12: "); queue.push_back(12);
System.out.println("queue push 11: "); queue.push_back(11);
System.out.println("queue push 21: "); queue.push_back(21);
System.out.println("queue push 31: "); queue.push_back(31);
System.out.print("queue log: "); queue.log();
System.out.println("front " + queue.front());
System.out.println("front " + queue.front());
System.out.print("clone queue log: "); queue.clone().log();
}
}
What I don't get about your implementation is the following:
in the front method you're using iter_, but nowhere else. What is it good for?
if you're not using some kind of variable to keep track of what was removed without actually removing it, technically you'd need to shift all the items of the array to the left by one position, such that the first item is gone. This however is an O(N) operation.
It's easier to implement a queue using a linked list instead of an array.
When building a queue using an array, you can make a cyclic "pointer" to the head of the array, that you can use to retrieve the top.
Popping from the array is simply done by increasing this cyclic pointer.
Maintain an int variable: top, and once you need to pop an element do top = (top + 1) % items_.length
Retrieving the head is simple using items_[top].
Make sure you are guarding against popping elements that are not there (popping from an empty array).
You will probably also need to maintan a size variable for the queue's size.
Below I share my proposed solution for a simple thread-safe FIFO queue :D
public class Queue extends Object {
private int numElements;
private Node first;
private Node last;
/**
* Helper linked list class
*/
private static class Node {
private Object item;
private Node next;
}
/**
* Creates a new Queue object.
*/
public Queue() {
numElements = 0;
first = last = null;
}
/**
* Puts an object at the end of the queue.
*
* #param object
*/
public void putObject(Object object) {
synchronized (this) {
Node newNode = new Node();
newNode.item = object;
newNode.next = null;
if ( numElements == 0 ) {
first = last = newNode;
} else {
last.next = newNode;
last = newNode;
}
numElements += 1;
}
}
/**
* Gets an object from the beginning of the queue. The object is removed
* from the queue. If there are no objects in the queue, returns null.
*/
public Object getObject() {
synchronized (this) {
Object item = null;
if ( numElements > 0 ) {
item = first.item;
first = first.next;
numElements -= 1;
if (numElements == 0) {
last = null;
}
}
return item;
}
}
}
You cant remove an element from an array like a List. You need to move the values up and set the last index of the array as null. Take a look at the source of a java class that implement Queue.remove() method. For example following is the code from removeAt(int index) method of ArrayBlockingQueue.
void removeAt(int i) {
final E[] items = this.items;
// if removing front item, just advance
if (i == takeIndex) {
items[takeIndex] = null;
takeIndex = inc(takeIndex);
} else {
// slide over all others up through putIndex.
for (;;) {
int nexti = inc(i);
if (nexti != putIndex) {
items[i] = items[nexti];
i = nexti;
} else {
items[i] = null;
putIndex = i;
break;
}
}
}
--count;
notFull.signal();
}
when you design a queue, you need to decide the priority like how you are going to add and remove element from it.You can go through this link and implement it similar to this.
FIFO
A typical example is :
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
public class QueueExample {
public static void main(String[] args) {
Queue<String> qe=new LinkedList<String>();
qe.add("b");
qe.add("a");
qe.add("c");
qe.add("e");
qe.add("d");
Iterator it=qe.iterator();
System.out.println("Initial Size of Queue :"+qe.size());
while(it.hasNext())
{
String iteratorValue=(String)it.next();
System.out.println("Queue Next Value :"+iteratorValue);
}
// get value and does not remove element from queue
System.out.println("Queue peek :"+qe.peek());
// get first value and remove that object from queue
System.out.println("Queue poll :"+qe.poll());
System.out.println("Final Size of Queue :"+qe.size());
}
}
First of all, you can't delete an item from an array, you can just overwrite it. You can use a List instead.
Another option is to use a circular queue, as amit's answer pointed out.
A simple solution using array is:
int queue[SIZE];
int first = 0;
int last = 0;
void enque(int i) {
if(last == SIZE)
throw new RuntimeExeption("Queue is full");
queue[last++] = i;
}
int deque() {
if(first == last)
throw new RuntimeExeption("Queue is empty");
return queue[first++];
}
Check this: it has enqueue and dequeue methods:
import java.io.*;
import java.lang.*;
class clrqueue
{
DataInputStream get=new DataInputStream(System.in);
int a[];
int i,front=0,rear=0,n,item,count=0;
void getdata()
{
try
{
System.out.println("Enter the limit");
n=Integer.parseInt(get.readLine());
a=new int[n];
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
void enqueue()
{
try
{
if(count<n)
{
System.out.println("Enter the element to be added:");
item=Integer.parseInt(get.readLine());
a[rear]=item;
rear++;
count++;
}
else
System.out.println("QUEUE IS FULL");
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
void dequeue()
{
if(count!=0)
{
System.out.println("The item deleted is:"+a[front]);
front++;
count--;
}
else
System.out.println("QUEUE IS EMPTY");
if(rear==n)
rear=0;
}
void display()
{
int m=0;
if(count==0)
System.out.println("QUEUE IS EMPTY");
else
{
for(i=front;m<count;i++,m++)
System.out.println(" "+a[i]);
}
}
}
class Myqueue
{
public static void main(String arg[])
{
DataInputStream get=new DataInputStream(System.in);
int ch;
clrqueue obj=new clrqueue();
obj.getdata();
try
{
do
{
System.out.println(" 1.Enqueue 2.Dequeue 3.Display 4.Exit");
System.out.println("Enter the choice");
ch=Integer.parseInt(get.readLine());
switch (ch)
{
case 1:
obj.enqueue();
break;
case 2:
obj.dequeue();
break;
case 3:
obj.display();
break;
}
}
while(ch!=4);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
This is the code i implemented and is working fine in my system.
import java.util.Arrays;
public class Queue {
public int[] queue = new int[3];
int head = -1, tail =-1;
public void enqueue(int N){
if(tail == (queue.length-1))
queue = Arrays.copyOf(queue,2*queue.length);
if(head == -1){
head++;
tail++;
queue[head] = N;
}
else {
tail++;
queue[tail] = N;
}
}
public int dequeue(){
if(head == -1)
throw new IllegalStateException("Cannot dequeue if queue is empty");
int firstItem = queue[head];
if (head == tail) {
head = -1;
tail = -1;
}
else
head++;
return firstItem;
}
public void display(){
for (int i = head; i<= tail ; i++){
System.out.println("Display: " + queue[i]);
}
}
}
public class Main {
public static void main(String[] args) {
Queue queue = new Queue();
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
queue.enqueue(40);
queue.display();
int dequeue = queue.dequeue();
System.out.println(dequeue);
queue.display();
int dequeue1 = queue.dequeue();
System.out.println(dequeue1);
queue.display();
}
}

Categories