Published on 20 abril 2011, by in C++.

Listas Dinamicas Lenguaje C

Hoy os pongo un pequeño programita que todos los que hemos estudiado informática y en concreto lenguaje C o C++ conoceremos.  Es un programa donde utilizamos estructuras dinámicas  y haciendo nuestra reserva de memoria  con la función malloc.

La lista es una agenda de teléfonos donde almacenamos en una estructura un nombre y un número. Mostramos el menú mediante la función “mostrar_menu ” con las opciones y creamos las dos funciones ” añadir_elemento ” y ” mostrar_lista “.

#include <stdio.h>
#include <stdlib.h>

void anadir_elementos();
void mostrar_lista();
void mostrar_menu();

struct agenda {

char nombre[20];
char tlf[9];
struct  agenda *sig;

}*primero;
struct agenda *ultimo;

int main()
{
//inicializamos las variables
primero=NULL;
ultimo=NULL;

int op;
do{

mostrar_menu();
scanf(“%d”,&op);
switch(op){

case 1: anadir_elementos();
break;
case 2: mostrar_lista();
break;
}
}while(op!=3);

system(“PAUSE”);
return 0;
}
void mostrar_menu(){

printf(“\nMENU\n”);
printf(“Anadir elemento escribe 1\n”);
printf(“Ver lista escribe 2\n”);
printf(“Pulse tres para salir\n”);

}
void anadir_elementos(){

struct agenda *nuevo;
nuevo=(struct agenda *)malloc(sizeof(struct agenda));
//lo contrario de nuevo==NULL , es para comprobar que se ha creado.
if(nuevo){
printf(“Introduce nombre”);
fflush(stdin);
gets(nuevo->nombre);
printf(“Introduce telefono”);
fflush(stdin);
gets(nuevo->tlf);
nuevo->sig=NULL;
}
if(primero==NULL){
primero=nuevo;
ultimo=nuevo;
}

else{
ultimo->sig=nuevo;
ultimo=nuevo;
}
}
void mostrar_lista(){

struct agenda *aux;
aux=primero;
if (primero==NULL) printf(“Lista vacia”);
else {
while (aux!=NULL){
printf(“%s %s\n”,aux->nombre,aux->tlf);
aux=aux->sig;
}

}
}

If you enjoyed this post, make sure you subscribe to my RSS feed!

Otros temas interesantes.

Sígueme en Twitter