// EJEMPLO DE LISTAS SENCILLAMENTE LIGADAS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct nodo
{
int numero;
struct nodo *sig;
};
struct nodo *start = NULL;
void PonEnLista(struct nodo *new)
{
// SE INSERTAN POR LA IZQUIERDA
if ( !start )
start = new;
else
{
new->sig = start;
start = new;
}
/*
// SE INSERTAN POR LA DERECHA ...
struct nodo *aux = start;
if ( !start )
start = new;
else
{
while(aux->sig) // ¿hay un siguiente?
aux = aux->sig;
aux->sig = new;
}
*/
}
void Guardar(char *cad)
{
struct nodo *new = (struct nodo*)malloc(sizeof(struct nodo));
new->numero = atoi(cad);
new->sig = NULL;
PonEnLista(new);
}
void MuestraLista( struct nodo *aux )
{
int k=0;
while (aux) // ¿estás apuntando a una localidad de memoria?
{ // ¿tienes datos?
printf("%d\n", aux->numero);
aux = aux->sig;
}
scanf("%d", &k);
}
void Borrar(int numero)
{
struct nodo *aux, *ant; // AUXiliar ANTerior
ant = aux = start;
while( aux ) // ¿existes?
{
if ( aux->numero == numero ) // ya se encontró
{
// ¿está al principio?
if ( aux == start )
{
start = start->sig;
free(aux); // se libera la memoria
break;
}
else // ¿eres el último?
if ( aux->sig == NULL )
{
ant->sig = NULL;
free(aux);
break;
}
else // está al en medio
{
ant->sig = aux->sig;
free(aux);
}
}
else
{
ant = aux;
aux = aux->sig;
}
}
}
void ciclo( )
{
char *cad = (char*)malloc(sizeof(char)*80);
while(1)
{
system("clear");
printf("==> ");
fgets(cad,80,stdin);
switch ( cad[0] )
{
case 103: // es una 'g' - g 23 (guardar)
cad++; cad++;
Guardar(cad);
break;
case 98: // es una 'b' - b 34 (borrar)
cad++; cad++;
Borrar( atoi(cad) );
break;
case 88: // es una 'X' - X ????
exit(0);
case 109: // es una 'm' - m ??? (mostrar)
MuestraLista(start);
break;
}
}
}
int main(int o, char **l) { ciclo();}