Listas Ligadas
Posted on June 17th, 2005 in C++, Código | No Comments »
Ejemplo de como se implementa y se usa una lista ligada en C++
listaLigada.h
C++:
-
/* listaLigada.h
-
*
-
* Encabezados de una lista ligada simple.
-
* Taboo
-
*/
-
-
#ifndef _LISTALIGADA_H
-
#define _LISTALIGADA_H
-
-
template<class A>
-
class Nodo
-
{
-
private:
-
A data;
-
Nodo* next;
-
public:
-
Nodo(): next(0){}
-
Nodo (A const& a):data(a), next(0){}
-
Nodo* getNext(){ return next; }
-
-
void setNext(Nodo *const& n)
-
{
-
next = n;
-
}
-
A getData(){ return data; }
-
-
};
-
-
template<class T>
-
class listaLigada
-
{
-
private:
-
Nodo<T> *_head;
-
int _size;
-
public:
-
listaLigada():_size(0), _head(0) {}
-
listaLigada(T const& t);
-
~listaLigada();
-
void insertaAlFinal(T const& t);
-
void insertaAlPrincipio(T const& t);
-
int size(){ return _size; }
-
void borraAlFinal();
-
void borraAlPrincipio();
-
Nodo<T>* head() const { return _head; }
-
bool empty(){ return _size == 0; }
-
-
friend ostream& operator <<(ostream &out, listaLigada &rhs)
-
{
-
Nodo<T> *ptr = rhs.head();
-
-
while(ptr!=0)
-
{
-
out <<ptr->getData() <<endl;
-
ptr = ptr->getNext();
-
}
-
-
return out;
-
}
-
};
-
-
#endif
listaLigada.cpp
C++:
-
#include <iostream.h>
-
#include <stdlib.h>
-
#include "listaLigada.h"
-
-
template<class A> listaLigada<A> :: listaLigada(A const& a)
-
{
-
Nodo<A> *theNew = new Nodo<A>(a);
-
_head = theNew;
-
_size = 1;
-
}
-
template<class A> listaLigada<A> :: ~listaLigada()
-
{
-
Nodo<A> *ptr = head();
-
Nodo<A> *aux;
-
-
while(ptr)
-
{
-
aux = ptr;
-
ptr = ptr->getNext();
-
delete aux;
-
}
-
}
-
template<class A> void listaLigada<A> :: insertaAlFinal(A const& a)
-
{
-
Nodo<A> *ptr = _head;
-
Nodo<A> *theNew = new Nodo<A>(a);
-
-
while(ptr->getNext()){ ptr++; }
-
ptr->setNext(theNew);
-
_size++;
-
}
-
-
-
int main()
-
{
-
listaLigada<int> yo(2);
-
-
yo.insertaAlFinal(3);
-
-
cout <<yo;
-
-
system("PAUSE");
-
return EXIT_SUCCESS;
-
}


