Ejemplo de como se implementa y se usa una lista ligada en C++

listaLigada.h

C++:
  1. /*  listaLigada.h
  2. *
  3. *  Encabezados de una lista ligada simple.
  4. *  Taboo   
  5. */
  6.  
  7. #ifndef _LISTALIGADA_H
  8. #define _LISTALIGADA_H
  9.  
  10. template<class A>
  11. class Nodo
  12. {
  13.      private:
  14.         A data;
  15.         Nodo* next;
  16.      public:
  17.         Nodo(): next(0){}
  18.         Nodo (A const& a):data(a), next(0){}
  19.         Nodo* getNext(){ return next; }
  20.  
  21.         void setNext(Nodo *const& n)
  22.         {
  23.              next = n;
  24.         }
  25.         A getData(){ return data; }
  26.  
  27. };
  28.  
  29. template<class T>
  30. class listaLigada
  31. {
  32.      private:
  33.           Nodo<T> *_head;
  34.           int _size;
  35.      public:
  36.             listaLigada():_size(0), _head(0) {}
  37.             listaLigada(T const& t);
  38.             ~listaLigada();
  39.             void insertaAlFinal(T const& t);
  40.             void insertaAlPrincipio(T const& t);
  41.             int size(){ return _size; }
  42.             void borraAlFinal();
  43.             void borraAlPrincipio();
  44.             Nodo<T>* head() const { return _head; }
  45.             bool empty(){ return _size == 0; }
  46.  
  47.             friend ostream& operator <<(ostream &out, listaLigada &rhs)
  48.             {
  49.                   Nodo<T> *ptr = rhs.head();
  50.  
  51.                   while(ptr!=0)
  52.                   {
  53.                         out <<ptr->getData() <<endl;
  54.                         ptr = ptr->getNext();
  55.                   }
  56.  
  57.                   return out;
  58.             }
  59. };
  60.  
  61. #endif

listaLigada.cpp

C++:
  1. #include <iostream.h>
  2. #include <stdlib.h>
  3. #include "listaLigada.h"
  4.  
  5. template<class A> listaLigada<A> :: listaLigada(A const& a)
  6. {
  7.      Nodo<A> *theNew = new Nodo<A>(a);
  8.      _head = theNew;
  9.      _size = 1;
  10. }
  11. template<class A> listaLigada<A> :: ~listaLigada()
  12. {
  13.      Nodo<A> *ptr = head();
  14.      Nodo<A> *aux;
  15.  
  16.      while(ptr)
  17.      {
  18.           aux = ptr;
  19.           ptr = ptr->getNext();
  20.           delete aux;
  21.      }
  22. }
  23. template<class A> void listaLigada<A> :: insertaAlFinal(A const& a)
  24. {
  25.      Nodo<A> *ptr = _head;
  26.      Nodo<A> *theNew = new Nodo<A>(a);
  27.  
  28.      while(ptr->getNext()){ ptr++; }
  29.      ptr->setNext(theNew);
  30.      _size++;
  31. }
  32.  
  33.  
  34. int main()
  35. {
  36.      listaLigada<int> yo(2);
  37.  
  38.      yo.insertaAlFinal(3);
  39.  
  40.      cout <<yo;
  41.  
  42.       system("PAUSE");
  43.       return EXIT_SUCCESS;
  44. }