Lista Simplemente Enlazada

Iniciado por [Z]tuX, Mayo 05, 2013, 09:15:02 PM

Tema anterior - Siguiente tema

0 Miembros y 1 Visitante están viendo este tema.

Hola, últimamente he estado trabajando mucho con listas dinámicas, así que hoy traigo un ejemplo de una lista Simplemente Enlazada en lenguaje C, el cual requiere de uso de apuntadores, no es nada del otro mundo si se tiene claro el concepto, por lo que si no conoces las Listas Simplemente Enlazadas, te recomiendo que leas este artículo de Wikipedia. No tienes permitido ver los links. Registrarse o Entrar a mi cuenta

Código: C

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

/* Ejemplo de Lista Simplemente Enlazada
* [Z]tuX
* http://ztux.blogspot.com/
*/

typedef struct Node{
    struct Node *next;
    int data;
}node;

node *newList(node *list);
node *insertInList(int data,node *list);
void showList(node *list);
int isEmpty(node *list);


int main(){
    node *LISTA = newList(LISTA);
    LISTA=insertInList(5,LISTA);
    LISTA=insertInList(6,LISTA);
    LISTA=insertInList(90,LISTA);
    LISTA=insertInList(0,LISTA);
    LISTA=insertInList(915,LISTA);
    showList(LISTA);
    return 0;
}

node *newList(node *list){
    return(list=NULL);
}

int isEmpty(node *list){
    return (list==NULL);
}

node * insertInList(int data,node *list){
    node * new_Node;
    new_Node = (node*)malloc(sizeof(node));
    node * aux;
    //First, check if the new node is not NULL
    if(new_Node!=NULL){
        new_Node->data=data;
        new_Node->next=NULL;
        if(isEmpty(list)){
            //If the list is empty...
            list=new_Node;
        }else{
            //If not is empty...
            aux = list;
            while(aux->next!=NULL){
                aux=aux->next;
            }
            aux->next=new_Node;
        }
    }else{
        printf("[!]There isn't space in memory...");
    }
    return list;
}

void showList(node *list){
    node *aux;
    for(aux=list;aux!=NULL;aux=aux->next){
        printf("Data: %d\n",aux->data);
    }
}


Salud[OS]