queue1.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// Link to Challenge: https://www.w3resource.com/cpp-exercises/queue/index.php
// Missing: Check if it is full
#include <iostream>
#include <vector>
using namespace std;
class Queue{
private:
struct node{
int data;
node* next;
};
node* head = nullptr;
bool isLinked = false;
public:
Queue(){
}
Queue(std::vector<int> arr){
enqueue(arr);
}
void enqueue(std::vector<int> arr){
node* pointing = nullptr;
node* tmp = nullptr;
for (int i = 0; i < arr.size(); i++){
if (head == nullptr){
head = new node{arr[i], nullptr};
}
else if (isLinked == false){
pointing = new node{arr[i], nullptr};
head -> next = pointing;
isLinked = true;
}
else {
tmp = new node{arr[i], nullptr};
pointing -> next = tmp;
pointing = pointing -> next;
}
}
}
void dequeue(){
if (is_empty()){
return;
}
else {
node* tmp = head;
head = head -> next;
delete tmp;
}
}
bool is_empty(){
return (head == nullptr);
}
void print(){
cout << "Queue Elements: ";
for (node* i = head; i != nullptr; i = i -> next){
cout << i -> data << " ";
}
cout << endl;
}
node* top(){
return head;
}
};
int main(){
Queue q1({5, 2, 3, 1, 4, 7, 9});
q1.print();
q1.dequeue();
q1.print();
cout << "Top: " + to_string(q1.top() -> data) << endl;
cout << "Is it empty?: " + to_string(q1.is_empty()) << endl;
return 0;
}
Console Output
1
2
3
4
Queue Elements: 5 2 3 1 4 7 9
Queue Elements: 2 3 1 4 7 9
Top: 2
Is it empty?: 0