Skip to content

Instantly share code, notes, and snippets.

@anil477
Created May 28, 2017 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anil477/fd0d0ab71ad09862ac1431e731b4ccf2 to your computer and use it in GitHub Desktop.
Save anil477/fd0d0ab71ad09862ac1431e731b4ccf2 to your computer and use it in GitHub Desktop.
Circulare Implementation For Queue Using Array
// A class to represent a queue
class Queue
{
int front, rear, size;
int capacity;
int array[];
public Queue(int n) {
capacity = n;
front = size = 0;
rear = capacity - 1;
array = new int[n];
}
// Queue is full when size becomes equal to the capacity
boolean isFull()
{ return (size == capacity);
}
// Queue is empty when size is 0
boolean isEmpty()
{ return (size == 0); }
// Method to add an item to the queue. It changes rear and size
void enqueue( int item)
{
if (isFull()){
System.out.println(" It's full ");
return;
}
rear = (rear + 1)%capacity;
array[rear] = item;
size = size + 1;
System.out.println(item + " enqueued to queue at index " + rear);
}
// Method to remove an item from queue. It changes front and size
int dequeue()
{
if (isEmpty())
return Integer.MIN_VALUE;
int item = array[front];
System.out.println( item + " dequeued at index " + front);
front = (front + 1)%capacity;
size = size - 1;
return item;
}
// Method to get front of queue
int front()
{
if (isEmpty())
return Integer.MIN_VALUE;
return array[front];
}
// Method to get rear of queue
int rear()
{
if (isEmpty())
return Integer.MIN_VALUE;
return array[rear];
}
// Method to get rear of queue
void status()
{
System.out.println(" Front :" + front);
System.out.println(" Rear :" + rear );
}
}
class Test
{
public static void main(String[] args)
{
Queue queue = new Queue(4);
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
queue.dequeue();
queue.dequeue();
queue.enqueue(40);
queue.status();
queue.enqueue(50);
queue.enqueue(60);
queue.status();
queue.enqueue(70);
queue.dequeue();
queue.dequeue();
queue.status();
queue.enqueue(70);
queue.status();
System.out.println("Front item is " + queue.front());
System.out.println("Rear item is " + queue.rear());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment