Created
January 8, 2026 13:30
-
-
Save m1irka/84d0408ecf3f08dae4d3946a3900f79f to your computer and use it in GitHub Desktop.
This file contains hidden or 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> | |
| using namespace std; | |
| template <typename T> | |
| struct Node { | |
| T data; | |
| Node* next; | |
| Node* prev; | |
| Node(const T& value) : data(value), next(nullptr), prev(nullptr) {} | |
| }; | |
| template <typename T> | |
| class Queue { | |
| private: | |
| Node<T>* head; | |
| Node<T>* tail; | |
| size_t count; | |
| public: | |
| Queue() : head(nullptr), tail(nullptr), count(0) {} | |
| ~Queue() { clear(); } | |
| void enqueue(const T& value) { | |
| Node<T>* newNode = new Node<T>(value); | |
| if (empty()) { | |
| head = tail = newNode; | |
| } | |
| else { | |
| tail->next = newNode; | |
| newNode->prev = tail; | |
| tail = newNode; | |
| } | |
| ++count; | |
| } | |
| void dequeue() { | |
| if (empty()) { | |
| cout << "Queue is empty!" << endl; | |
| return; | |
| } | |
| Node<T>* temp = head; | |
| head = head->next; | |
| if (head) head->prev = nullptr; | |
| else tail = nullptr; | |
| delete temp; | |
| --count; | |
| } | |
| T front() const { | |
| if (empty()) { | |
| throw runtime_error("Queue is empty!"); | |
| } | |
| return head->data; | |
| } | |
| bool empty() const { return count == 0; } | |
| size_t size() const { return count; } | |
| void clear() { | |
| while (!empty()) { | |
| dequeue(); | |
| } | |
| } | |
| void print() const { | |
| Node<T>* temp = head; | |
| cout << "( "; | |
| while (temp) { | |
| cout << temp->data; | |
| if (temp->next) cout << ", "; | |
| temp = temp->next; | |
| } | |
| cout << " )" << endl; | |
| } | |
| }; | |
| int main() { | |
| Queue<int> q; | |
| q.enqueue(1); | |
| q.enqueue(2); | |
| q.enqueue(3); | |
| cout << "Queue: "; | |
| q.print(); | |
| cout << "Front: " << q.front() << endl; | |
| cout << "Size: " << q.size() << endl; | |
| q.dequeue(); | |
| cout << "After dequeue: "; | |
| q.print(); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment