Queue
Step through a C++ queue built from nodes.
Everything is simulated in this browser; nothing is sent to any server.
Values
Create the new node
Create the new node
n_ = 0
The queue is empty
- Just added
- Leaving now
Step 1 / 54
Code
#include <iostream>
using namespace std;
class Nodo { // A node holds the data and a pointer to the next one
private: // Private attributes: only the methods touch them
int dato;
Nodo* siguiente;
public:
Nodo(int d) : dato(d), siguiente(nullptr) {}
int getDato() const { return dato; }
Nodo* getSiguiente() const { return siguiente; }
void setDato(int d) { dato = d; }
void setSiguiente(Nodo* s) { siguiente = s; }
};
class Cola {
private: // frente_ is the next to leave and final_ the last to arrive
Nodo* frente_; // First node of the queue
Nodo* final_; // Last node of the queue
int n_; // Number of nodes
public:
Cola() : frente_(nullptr), final_(nullptr), n_(0) {}
// Destructor (no se anima)
~Cola() {
while (frente_ != nullptr) desencolar();
}
void encolar(int valor) { // Enqueue at the back: O(1)
Nodo* nuevo = new Nodo(valor); // Create the node
if (final_ == nullptr) { // Is the queue empty?
frente_ = final_ = nuevo; // It is the only node: frente_ and final_ point to it
} else {
final_->setSiguiente(nuevo); // The last node points to the new one
final_ = nuevo; // final_ now points to the new node
}
n_++;
}
void desencolar() { // Dequeue the front: O(1)
if (frente_ == nullptr) return; // Empty queue: nothing to remove
Nodo* temp = frente_; // Keep the front so it can be freed
frente_ = frente_->getSiguiente(); // frente_ moves on to the next node
if (frente_ == nullptr) final_ = nullptr; // Queue is empty: final_ no longer points to anything
delete temp; // Free the memory
n_--;
}
// Muestra la cola del frente al final
void imprimir() const {
cout << "frente ->";
for (Nodo* p = frente_; p != nullptr; p = p->getSiguiente())
cout << " " << p->getDato();
cout << endl;
}
};
int main() {
Cola cola;
cola.encolar(3);
cola.encolar(6);
cola.encolar(9);
cola.imprimir(); // frente -> 3 6 9
cola.desencolar();
cola.imprimir(); // frente -> 6 9
cola.encolar(1);
cola.imprimir(); // frente -> 6 9 1
return 0;
}