-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueue.cpp
More file actions
100 lines (77 loc) · 2.08 KB
/
queue.cpp
File metadata and controls
100 lines (77 loc) · 2.08 KB
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
#include <iostream>
// Classe que implementa uma fila utilizando a estrutura de lista encadeada.
template <typename T>
class Fila{
private:
// Classe que representa um nó da fila.
struct No{
T valor; /*< O valor armazenado no nó. */
No* next; /*< Ponteiro para o próximo nó. */
No(T value) : valor(value), next(NULL){}
};
No* head; /*< Ponteiro para o primeiro elemento da fila. */
No* tail; /*< Ponteiro para o último elemento da fila. */
public:
// Construtor da classe Fila.
Fila() : head(NULL), tail(NULL){}
// Destrutor da classe Fila.
~Fila(){
while(!isEmpty()) {
dequeue();
}
}
// Verifica se a fila está vazia.
bool isEmpty() const {
if(head == NULL){
return true;
}else{
return false;
}
}
// Adiciona um elemento no final da fila.
void enqueue(T value){
No* newNo = new No(value);
if(isEmpty()){
head = tail = newNo;
}else{
tail->next = newNo;
tail = newNo;
}
}
// Remove o elemento na frente da fila.
void dequeue(){
if(isEmpty()){
std::cout << "A fila está vazia." << std::endl;
return;
}
No* temp = head;
head = head->next;
if(head == NULL){
tail = NULL;
}
delete temp;
}
// Retorna o elemento da frente da fila.
T& peek(){
if (isEmpty()) {
throw std::runtime_error("A fila está vazia.");
}
return head->valor;
}
};
int main() {
Fila<int> fila;
fila.enqueue(1);
fila.enqueue(2);
fila.enqueue(3);
std::cout << "Elemento da frente: " << fila.peek() << std::endl;
fila.dequeue();
std::cout << "Elemento da frente após remover: " << fila.peek() << std::endl;
fila.enqueue(4);
fila.enqueue(5);
while (!fila.isEmpty()) {
std::cout << "Elemento removido: " << fila.peek() << std::endl;
fila.dequeue();
}
return 0;
}