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
91
92
93
94
95
96
97
98
99
100
101
102
103
|
// Link to Challenge: https://www.w3resource.com/cpp-exercises/queue/index.php
#include <iostream>
#include <vector>
using namespace std;
class Queue{
private:
struct node{
int data;
node* next;
};
node* head = nullptr;
node* current = nullptr; // current has to be on the global side
// because if I were to enqueue separately, current
// would just be nullptr every single time and doesn't get
// stored as current = head, which creates a seg fault
public:
Queue(){
}
Queue(std::vector<int> arr){
enqueue(arr);
}
void enqueue(std::vector<int> arr){
node* tmp = nullptr;
current = nullptr;
for (int i = 0; i < arr.size(); i++){
if (head == nullptr){
head = new node{arr[i], nullptr};
current = head;
}
else {
tmp = new node{arr[i], nullptr};
current -> next = tmp;
current = current -> next;
}
}
}
void enqueue(int a){
node* tmp = nullptr;
if (head == nullptr){
head = new node{a, nullptr};
current = head;
}
else {
tmp = new node{a, nullptr};
current -> next = tmp;
current = current -> next;
}
}
void dequeue(){
node* tmp = head;
head = head -> next;
tmp -> next = nullptr;
delete tmp;
}
void print(){
cout << "Queue Elements: ";
for (node* i = head; i != nullptr; i = i -> next){
cout << i -> data << " ";
}
cout << endl;
}
void dequeue_all(){
while (head != nullptr){
node* tmp = head;
head = head -> next;
// tmp -> next = nullptr;
delete tmp;
}
}
void copy(const Queue& other){
dequeue_all();
for (node* i = other.head; i != nullptr; i = i -> next){
enqueue({i -> data});
}
}
};
int main(){
Queue q1({1, 2, 3, 4, 5});
q1.print();
Queue q2({6, 10, 14, 12});
q2.print();
q1.copy(q2);
q1.print();
q2.print();
return 0;
}
|