Skip to content

Instantly share code, notes, and snippets.

@misterpoloy
Created January 16, 2020 23:19
Show Gist options
  • Save misterpoloy/9ccabb3f866830be7ac6568b726a486e to your computer and use it in GitHub Desktop.
Save misterpoloy/9ccabb3f866830be7ac6568b726a486e to your computer and use it in GitHub Desktop.
Queue Implementation using a linked list
// https://www.youtube.com/watch?v=A5_XdiK4J8A&list=PL2_aWCzGMAwI3W_JlcBbtYTwiQSsOTa6P&index=24
#include <iostream>
struct Node {
int value;
Node* next;
Node(int x)
: next(nullptr), value(x)
{
}
};
class Queue {
private:
Node* head;
Node* rear;
public:
Queue() {
head = rear = nullptr;
}
void EnQueue(int value) {
Node* temp = new Node(value);
if (IsEmpty()) {
head = rear = temp;
return;
}
rear->next = temp;
rear = temp;
}
bool IsEmpty() {
return (head == nullptr && rear == nullptr) ? true : false;
}
void DeQueue() {
if (IsEmpty()) {
std::cout << "Error!" << std::endl;
return;
}
Node* temp = head;
head = head->next;
delete temp;
}
void Print() {
Node* temp = head;
while (temp != nullptr) { // <- Remember because I always forgot!!
std::cout << temp->value << std::endl;
temp = temp->next;
}
}
};
int main() {
Queue Q;
Q.EnQueue(1);
Q.EnQueue(2);
Q.EnQueue(3);
Q.Print();
std::cout << "dequeue" << std::endl;
Q.DeQueue();
Q.Print();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment