Skip to content

Instantly share code, notes, and snippets.

@npocmaka
Last active December 15, 2016 14:39
Show Gist options
  • Save npocmaka/12c7bc029b23b4495bb93866e6e01d4c to your computer and use it in GitHub Desktop.
Save npocmaka/12c7bc029b23b4495bb93866e6e01d4c to your computer and use it in GitHub Desktop.
// ConsoleApplication11.cpp : main project file.
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
using namespace std;
const int MAX_SIZE = 100;
class ArrayQueue
{
private:
int data[MAX_SIZE];
int front;
int rear;
public:
ArrayQueue()
{
front = -1;
rear = -1;
}
int Size()
{
if (rear == -1) {
return 0;
}
if (rear < front)
{
return MAX_SIZE - (front - rear) + 1;
}
return rear - front + 1;
}
void Enqueue(int element)
{
// Don't allow the queue to grow more
// than MAX_SIZE - 1
if (Size() == MAX_SIZE) {
cout << "Max size reached\n";
return;
}
// MOD is used so that rear indicator
// can wrap around
rear = (rear+1) % MAX_SIZE;
data[rear] = element;
if (front == -1) {
front = 0;
}
}
int Dequeue()
{
if (isEmpty()) {
cout << "queue is empty!\n";
return -1;
}
int ret = data[front];
// if the last element is dequeued
// queue is turned in it's initial state
if (front == rear) {
front = -1;
rear = -1;
return ret;
}
// MOD is used so that front indicator
// can wrap around
front = (front+1) % MAX_SIZE;
return ret;
}
int Front()
{
if (isEmpty()) {
cout << "Queue is empty\n";
return -1;
}
return data[front];
}
bool isEmpty()
{
return (rear == -1) ? true : false;
}
};
int main()
{
ArrayQueue q;
if (q.isEmpty())
{
cout << "Queue is empty" << endl;
}
// Enqueue elements
q.Enqueue(100);
q.Enqueue(200);
q.Enqueue(300);
cout << q.Dequeue() << "(100?)\n";
cout << q.Dequeue() << "(200?)\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment