Skip to content

Instantly share code, notes, and snippets.

@misterpoloy
Created January 16, 2020 22:36
Show Gist options
  • Save misterpoloy/d5fd8cd2f0d049ddeb882c430c793389 to your computer and use it in GitHub Desktop.
Save misterpoloy/d5fd8cd2f0d049ddeb882c430c793389 to your computer and use it in GitHub Desktop.
Queue Integer Implementation
// TODO, I can use templates to make it more generic?
// https://www.youtube.com/watch?v=okr-XE8yTO8&list=PL2_aWCzGMAwI3W_JlcBbtYTwiQSsOTa6P&index=23
#include <iostream>
#define MAX_SIZE 5
class Queue {
private:
int Data[MAX_SIZE];
int head, rear;
public:
Queue() {
head = rear = -1;
}
void EnQueue(int i) {
if(isFull())
{
std::cout<< "Error: Queue is Full \n";
return;
}
if (isEmpty()) {
head = rear = 0;
Data[rear] = i;
} else {
// Increment rear to next value
rear = (rear + 1) % MAX_SIZE;
}
Data[rear] = i;
}
void DeQueue() {
if (isEmpty()) {
std::cout << "Error!" << std::endl;
return;
}
else if (head == rear) {
head = rear = -1;
}
else {
head = (head + 1) % MAX_SIZE;
}
}
bool isEmpty() {
if (head == -1 && rear == -1)
return true;
return false;
}
bool isFull() {
// Does the **last item NEXT** == to the first
return (rear + 1) % MAX_SIZE == head ? true : false;
}
int Front() {
if (head == -1) {
std::cout << "List is empty!" << std::endl;
return -1;
}
return Data[head];
}
void Print() {
int count = (rear + MAX_SIZE - head) % MAX_SIZE + 1;
std::cout << "Queue: " << std::endl;
for (int i = 0; i < count; i++) {
int index = (head + i) % MAX_SIZE;
std::cout << Data[index] << " ";
}
std::cout << "\n";
}
};
int main() {
Queue Q;
Q.EnQueue(1); // Add 1
Q.EnQueue(2); // Add 2
Q.EnQueue(3); // Add 2
Q.DeQueue(); // Remove first element
std::cout << "Front is " << Q.Front() << std::endl;
Q.Print();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment