top of page

Circular Queue

Circular Queue is also a linear data structure, which follows the principle of FIFO(First In First Out), but instead of ending the queue at the last position, it again starts from the first position after the last, hence making the queue behave like a circular data structure.Circular queue avoids the wastage of space in a regular queue.


Implementation using Java:

public class Queue {
	private int data[];
	private int front;
	private int rear;
	private int size;
	public Queue()
	{
		data= new int[5];
		front=-1;
		rear=-1;
	}
	public int size()
	{
		return size;
	}
	public boolean isEmpty()
	{
		if(size==0)
			return true;
		else
			return false;
	}
	public int front() throws QueueEmptyException
	{
		if(size==0)
		{
			throw new QueueEmptyException();
		}
		return data[front];
	}
	public void enqueue(int element) throws QueueFullException
	{
		if(size==data.length)
		{
			throw new QueueFullException();
		}
		if(size==0)
		{
			front=0;
		}
		rear=(rear+1)%data.length;
		data[rear]=element;
		size++;
	}
	public int dequeue() throws QueueEmptyException
	{
		if(size==0)
		{
			throw new QueueEmptyException();
		}
		int temp=data[front];
		front=(front+1)%data.length;
		size--;
		if(size==0)
		{
			front=-1;
			rear=-1;
		}
		return temp;
	}
	public static void main(String args[])
	{
		Queue q=new Queue();
			try
			{
				q.enqueue(10);
				q.enqueue(20);
				q.enqueue(30);
				q.enqueue(40);
				q.enqueue(50);
			}catch(QueueFullException e)
			{
				System.out.println(e);
			}
			try
			{
				q.dequeue();
				q.dequeue();
			}catch(QueueEmptyException e)
			{
				System.out.println(e);
			}
			 try {
			q.enqueue(60);
			q.enqueue(70);
	        	}catch(QueueFullException e)
			{
				System.out.println(e);
			}
	        	System.out.println("Succesfully inserted");
	 } 
}	

 

Happy Coding!

Follow us on Instagram @programmersdoor

Join us on Telegram @programmersdoor


Please write comments if you find any bug in above code/algorithm, or find other ways to solve the same problem.

Follow Programmers Door for more.

14 views0 comments

Recent Posts

See All
bottom of page