Skip to content

Instantly share code, notes, and snippets.

@leopic
Created June 17, 2013 00:11
Show Gist options
  • Select an option

  • Save leopic/5793953 to your computer and use it in GitHub Desktop.

Select an option

Save leopic/5793953 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
char* getStr();
int getId();
int menu();
void clearBuffer();
void contarNodos();
void imprimirLista();
void setPersona();
struct persona {
int id;
char *nombre;
struct persona *siguiente;
};
struct persona *lista;
struct persona *nodoTemp;
main() {
lista = (struct persona*) malloc(sizeof(struct persona));
return menu();
}
int menu() {
char c;
nodoTemp = (struct persona*) malloc(sizeof(struct persona));
do {
printf("~~ MENU ~~\nHaga una seleccion:\n 1. Ingresar nuevo nodo.\n 2. Imprimir la lista.\n 3. Contar los nodos.\n q: salir.\n ");
c = getchar();
switch(c) {
case '1':
setPersona();
break;
case '2':
imprimirLista();
break;
case '3':
contarNodos();
break;
default:
break;
}
} while(c != 'q' && c != EOF);
}
int getId() {
int num;
printf("Ingrese el ID: (0 ~ 9): ");
scanf("%d" , &num);
return num;
}
// retorna un nuevo puntero a un arreglo
char* getStr() {
char d,
*newAr;
int i = 0;
newAr = (char*) malloc(sizeof(char)*100);
printf("\nIngrese el nombre: ");
while((d = getchar()) != EOF && d != '\n') {
newAr[i++] = d;
}
return newAr;
}
void setPersona() {
struct persona *actual;
actual = (struct persona*) malloc(sizeof(struct persona));
clearBuffer();
actual->nombre = getStr();
actual->id = getId();
// si es el primer nodo
if (lista->siguiente == 0) {
lista->siguiente = actual;
} else {
nodoTemp->siguiente = actual;
}
nodoTemp = actual;
clearBuffer();
}
void imprimirLista() {
struct persona *temporal;
if (lista->siguiente) {
temporal = lista->siguiente;
printf("Imprimiendo lista \n");
while(temporal) {
printf("id:\t%d\n", temporal->id);
printf("nom:\t%s\n", temporal->nombre);
temporal = temporal->siguiente;
}
} else {
printf("la lista esta vacia.\n\n");
}
clearBuffer();
}
void contarNodos() {
struct persona *temporal;
temporal = lista->siguiente;
int i = 0;
while(temporal) {
i++;
temporal = temporal->siguiente;
}
printf("Total: %d nodos.\n", i);
clearBuffer();
}
// http://cboard.cprogramming.com/c-programming/92513-cin-ignore-c.html
// http://stackoverflow.com/questions/10199897/cin-getline-is-skipping-an-input-in-c
// cuando se manejan menus que tienen breaklines, se ocupa limpiar el buffer
// antes de empezar a leer caracteres
void clearBuffer() {
while(getchar() != '\n')
;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment