Stack

Step through a C++ stack 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 stack is empty

  • Just added
  • Leaving now

Step 1 / 47

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 Pila {
private: // The last pushed node is the top
Nodo* cima_; // Top node
int n_; // Number of nodes
public:
Pila() : cima_(nullptr), n_(0) {}
// Destructor (no se anima)
~Pila() {
while (cima_ != nullptr) desapilar();
}
void apilar(int valor) { // Push on top: O(1)
Nodo* nuevo = new Nodo(valor); // Create the node
nuevo->setSiguiente(cima_); // The new node points to the old top
cima_ = nuevo; // cima_ now points to the new node
n_++;
}
void desapilar() { // Pop the top: O(1)
if (cima_ == nullptr) return; // Empty stack: nothing to remove
Nodo* temp = cima_; // Keep the top so it can be freed
cima_ = cima_->getSiguiente(); // cima_ moves down to the next node
delete temp; // Free the memory
n_--;
}
// Muestra la pila de la cima a la base
void imprimir() const {
cout << "cima ->";
for (Nodo* p = cima_; p != nullptr; p = p->getSiguiente())
cout << " " << p->getDato();
cout << endl;
}
};
int main() {
Pila pila;
pila.apilar(3);
pila.apilar(6);
pila.apilar(9);
pila.imprimir(); // cima -> 9 6 3
pila.desapilar();
pila.imprimir(); // cima -> 6 3
pila.apilar(1);
pila.imprimir(); // cima -> 1 6 3
return 0;
}