TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
queue.hpp
1/* This class specifies the basic operation on a queue as a linked list */
2#ifndef DATA_STRUCTURES_QUEUE_HPP_
3#define DATA_STRUCTURES_QUEUE_HPP_
4
5#include "node.hpp"
6
8template <class ValueType>
9class queue {
11
12 public:
13 using value_type = ValueType;
17 void display() const {
18 std::cout << "Front --> ";
19 display_all(this->queueFront.get());
20 std::cout << '\n';
21 std::cout << "Size of queue: " << size << '\n';
22 }
23
29 std::vector<value_type> toVector() const {
30 return push_all_to_vector(this->queueFront.get(), this->size);
31 }
32
33 private:
38 void ensureNotEmpty() const {
39 if (isEmptyQueue()) {
40 throw std::invalid_argument("Queue is empty.");
41 }
42 }
43
44 public:
49 bool isEmptyQueue() const { return (queueFront == nullptr); }
50
54 void enQueue(const value_type& item) {
55 auto newNode = std::make_shared<node_type>();
56 newNode->data = item;
57 newNode->next = nullptr;
58 if (isEmptyQueue()) {
59 queueFront = newNode;
60 queueRear = newNode;
61 } else {
62 queueRear->next = newNode;
63 queueRear = queueRear->next;
64 }
65 ++size;
66 }
67
72 value_type front() const {
74 return queueFront->data;
75 }
76
81 void deQueue() {
83 queueFront = queueFront->next;
84 --size;
85 }
86
90 void clear() {
91 queueFront = nullptr;
92 queueRear = nullptr;
93 size = 0;
94 }
95
96 private:
97 std::shared_ptr<node_type> queueFront =
98 {};
99 std::shared_ptr<node_type> queueRear =
100 {};
101 std::size_t size = 0;
102};
103
104#endif // DATA_STRUCTURES_QUEUE_HPP_
Definition queue.hpp:9
void display() const
prints the queue into the std::cout
Definition queue.hpp:17
std::vector< value_type > toVector() const
converts the queue into the std::vector
Definition queue.hpp:29
bool isEmptyQueue() const
checks if the queue has no elements
Definition queue.hpp:49
void clear()
removes all elements from the queue
Definition queue.hpp:90
value_type front() const
Definition queue.hpp:72
std::shared_ptr< node_type > queueRear
Definition queue.hpp:99
void ensureNotEmpty() const
throws an exception if queue is empty
Definition queue.hpp:38
void enQueue(const value_type &item)
inserts a new item into the queue
Definition queue.hpp:54
void deQueue()
removes the first element from the queue
Definition queue.hpp:81
std::shared_ptr< node_type > queueFront
Definition queue.hpp:97
Provides Node class and related utilities.