Created
June 16, 2018 21:16
-
-
Save alexnoz/165cf92a45984d88b91472a91fadf7a3 to your computer and use it in GitHub Desktop.
A queue implementation using linked lists
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> | |
struct Node { | |
int data; | |
Node* next; | |
}; | |
class Queue { | |
private: | |
Node* head = nullptr; | |
Node* tail = nullptr; | |
public: | |
~Queue() { | |
Node* temp = head; | |
while (temp) { | |
Node* next = temp->next; | |
delete temp; | |
temp = next; | |
} | |
} | |
bool enqueue(int data) { | |
Node* temp = new Node { data, nullptr }; | |
if (!head && !tail) { | |
head = tail = temp; | |
return true; | |
} | |
tail->next = temp; | |
tail = temp; | |
return true; | |
} | |
bool dequeue() { | |
if (!head) return false; | |
else if (head == tail) { | |
head = tail = nullptr; | |
return true; | |
} | |
Node* temp = head; | |
head = head->next; | |
delete temp; | |
return true; | |
} | |
int front() { | |
if (!head) throw std::out_of_range("The queue is empty"); | |
return head->data; | |
} | |
bool isEmpty() { | |
return !head; | |
} | |
void print() { | |
Node* temp = head; | |
while (temp) { | |
std::cout << temp->data << "\n"; | |
temp = temp->next; | |
} | |
} | |
}; | |
int main() { | |
Queue q; | |
q.enqueue(2); | |
q.enqueue(5); | |
q.enqueue(6); | |
q.enqueue(6); | |
q.enqueue(5); | |
q.enqueue(2); | |
q.dequeue(); | |
q.dequeue(); | |
q.print(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment