Last active
June 27, 2018 20:58
-
-
Save alexnoz/c0482d6ada1e7a0ed1f234096ac725a5 to your computer and use it in GitHub Desktop.
A queue implementation using a circular array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <stdexcept> | |
class Queue { | |
private: | |
int length = 0; | |
int front = -1; | |
int rear = -1; | |
int *queue = nullptr; | |
public: | |
Queue(int _length) { | |
length = _length; | |
queue = new int[length]; | |
} | |
~Queue() { | |
delete[] queue; | |
} | |
bool isEmpty() { | |
return front == -1 && rear == -1; | |
} | |
bool isFull() { | |
return (rear + 1) % length == front; | |
} | |
bool enqueue(int n) { | |
if (isEmpty()) front = 0; | |
else if (isFull()) return false; | |
rear = (rear + 1) % length; | |
queue[rear] = n; | |
return true; | |
} | |
bool dequeue() { | |
if (isEmpty()) return false; | |
if (front == 0 && rear == 0) { | |
front = rear = -1; | |
return true; | |
} | |
front = (front + 1) % length; | |
return true; | |
} | |
int peek() { | |
if (isEmpty()) throw std::range_error("The queue is empty"); | |
return queue[front]; | |
} | |
void print() { | |
int i = front; | |
while (1) { | |
std::cout << *(queue + i) << "\n"; | |
if (i == rear) break; | |
i = (i + 1) % length; | |
} | |
} | |
}; | |
int main() { | |
Queue q(10); | |
q.enqueue(5); | |
q.enqueue(2); | |
q.enqueue(6); | |
q.enqueue(1); | |
q.enqueue(3); // 5 2 6 1 3 _ _ _ _ _ | |
q.dequeue(); // _ 2 6 1 3 _ _ _ _ _ | |
q.enqueue(9); // _ 2 6 1 3 9 _ _ _ _ | |
q.dequeue(); // _ _ 6 1 3 9 _ _ _ _ | |
q.enqueue(7); // _ _ 6 1 3 9 7 _ _ _ | |
q.dequeue(); // _ _ _ 1 3 9 7 _ _ _ | |
q.enqueue(1); // _ _ _ 1 3 9 7 1 _ _ | |
q.dequeue(); // _ _ _ _ 3 9 7 1 _ _ | |
q.enqueue(4); // _ _ _ _ 3 9 7 1 4 _ | |
q.dequeue(); // _ _ _ _ _ 9 7 1 4 _ | |
q.enqueue(8); // _ _ _ _ _ 9 7 1 4 8 | |
q.dequeue(); // _ _ _ _ _ _ 7 1 4 8 | |
q.enqueue(5); // 5 _ _ _ _ _ 7 1 4 8 | |
q.print(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment