Implementation of Circular Queue
To overcome the issues related to the spaces of the queue we will use a circular queue.
Circular Queue Implementation:
class MyCircularQueue
{
public:
vector<int> v;
int rear;
int front;
/** Initialize your data structure here. Set the size of the queue to be k. */
MyCircularQueue(int k)
{
v.resize(k + 1);
front = 0;
rear = 0;
}
/** Insert an element into the queue.Return true if the operation is successful.*/
bool enQueue(int value)
{
int len = v.size();
if (((rear + 1) % len) == front)
{
return false;
}
rear = (rear + 1) % len;
v[rear] = value;
return true;
}
/** Delete an element from the queue.Return true if the operation is successful.*/
bool deQueue()
{
int len = v.size();
if (front == rear)
{
return false;
}
front = (front + 1) % len;
v[front] = 0;
return true;
}
/** Get the front item from the queue. */
int Front()
{
int len = v.size();
if (isEmpty())
{
return -1;
}
int pos = (front + 1) % len;
return v[pos];
}
/** Get the last item from the queue. */
int Rear()
{
if (isEmpty())
{
return -1;
}
return v[rear];
}
/** Checks whether the circular queue is empty or not. */
bool isEmpty()
{
bool res = false;
if (front == rear)
{
res = true;
}
return res;
}
/** Checks whether the circular queue is full or not. */
bool isFull()
{
bool res = false;
int len = v.size();
if (((rear + 1) % len) == front)
{
res = true;
}
return res;
}
};
Last updated