Skip to content

Instantly share code, notes, and snippets.

@abdoei
Created August 31, 2023 21:24
Show Gist options
  • Save abdoei/a35a1d0fd55bcf51daf5dd9e9964f45f to your computer and use it in GitHub Desktop.
Save abdoei/a35a1d0fd55bcf51daf5dd9e9964f45f to your computer and use it in GitHub Desktop.
My implementation of the queue data structure
#include <iostream>
using namespace std;
template <class T>
class Queue
{
struct Node
{
T value;
Node *next = NULL;
};
Node *front, *rear;
int length = 0;
public:
Queue() : front(nullptr), rear(nullptr) {}
~Queue() {
this->clear();
}
bool isEmpty()
{
return (this->rear == NULL);
}
void enqueue(T v) {
Node *tmp = new Node;
if (tmp == NULL)
cout << "Stack::push(T v) can't allocate memory\n";
else {
++length;
if(isEmpty()){
front = new Node;
front->value = v;
front->next = NULL;
rear = front;
}
else{
Node* tmp = new Node;
tmp->value = v;
tmp->next = NULL;
rear->next = tmp;
rear = tmp;
}
}
}
void dequeue(){
if (isEmpty()) {
cout << "Can't dequeue an empty queue" << endl;
}
else {
if(length == 1){
front->next = NULL;
front = rear = NULL;
}
else{
Node* tmp = front;
front = front->next;
tmp->next = NULL;
delete tmp;
}
--length;
}
}
T getFront()
{
if (isEmpty())
{
cout << "can't getTop() an empty stack\n";
return -1;
}
else
return front->value;
}
T getRear()
{
if (isEmpty())
{
cout << "can't getTop() an empty stack\n";
return -1;
}
else
return rear->value;
}
void clear()
{
if (isEmpty())
return;
else
{
Node *tmp;
while (front != NULL)
{
tmp = front;
front = front->next;
tmp->next = NULL; // for safty reasons
delete tmp;
}
rear = NULL;
}
}
void disp()
{
Node *cur = front;
cout << '[';
while (cur != NULL)
{
cout << cur->value << " ";
cur = cur->next;
}
cout << ']';
}
};
int main()
{
Queue<int> q;
q.enqueue(2);
q.enqueue(4);
q.enqueue(6);
q.enqueue(8);
q.enqueue(10);
q.enqueue(12);
// q.disp();
// cout << q.getFront() << ',' << q.getRear();
q.enqueue(14);
q.clear();
q.disp();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment