Il codice che segue mostra come creare uno stack utilizzando semplicemente una lista concatenata.
I nodi hanno questa forma:

struct node
{
	T data;
	node* down;
};

dove data indica il dato effettivamente contenuto, e down indica l’elemento subito in basso all’elemento corrente nella pila

Le operazioni top e pop non possono essere effettuate, ovviamente, in caso di stack vuoto. Per questo motivo lanciano un’eccezione.

#include <iostream>
#include <stdexcept>

using namespace std;

template <typename T>
class Stack
{
	private:
		struct node
		{
			T data;
			node* down;
		};

		node* topNode;

	public:
		Stack();
		void push(T newData);
		void pop();
		T top();
		bool isEmpty();
		void print();
};

template <typename T>
Stack<T>::Stack()
{
	this->topNode = NULL;
}

template <typename T>
void Stack<T>::push(T newData)
{
	node* newNode = new node;

	newNode->data = newData;
	newNode->down = this->topNode;

	this->topNode = newNode;
}

template <typename T>
void Stack<T>::pop()
{
	if(this->topNode == NULL)
	{
		throw underflow_error("Stack vuoto");
	}
	else
	{
		node* downItem = topNode->down;
		delete this->topNode;
		this->topNode = downItem;
	}
}

template <typename T>
T Stack<T>::top()
{
	if(this->topNode != NULL)
		return this->topNode->data;
	else
		throw runtime_error("Stack vuoto");
}

template <typename T>
bool Stack<T>::isEmpty()
{
	return this->topNode == NULL;
}

template <typename T>
void Stack<T>::print()
{
	node* iter = this->topNode;

	cout << "{";
	while(iter != NULL)
	{
		cout << iter->data;
		iter = iter->down;

		if(iter != NULL)
			cout << " -> ";
	}

	cout << "}";
}

int main()
{
	Stack<int> stack;

	try {
		stack.top(); // lancia un'eccezione
	}
	catch(runtime_error& e)
	{
		cout << e.what() << endl << endl;
	}

	for(int i = 0; i <= 10; i++)
		stack.push(i);

	stack.print();
	cout << endl << endl;

	while(!stack.isEmpty())
	{
		cout << "Pop item: " << stack.top() << endl;
		stack.pop();
	}

	try {
		stack.pop();
	}
	catch(underflow_error& e)
	{
		cout << endl << endl << e.what() << endl << endl;
	}

	return 0;
}