Search code examples
clinked-listnestedfill

How to deal with nested list?


H. I'm writting program to analyse code in pascal. I've created such lined-lists

typedef struct lista1   //list which contains var, const and types!
{
    int rodzaj; //1 - variables, 2 - constants, 3 - types
    char nazwa[128];
    char add[128];
    struct lista1 *wsk;
}lista1;

typedef struct lista2
{
    int rodzaj; //1 - procedures, 2 - functions
    char nazwa[128];
    char typ[128];
    struct lista2 *wsk;
    lista1 *var_loc;
    lista1 *const_loc;
    lista1 *type_loc;
}lista2;

my question is: how to fill those nested lists(var_loc, const_loc, type_loc)? I've tried to do some function in this purpose but I have lot of errors. Please, show me how to do it.


Solution

  • This code creates an external list (head) with 5 elements, each of them with an internal list of 10 elements:

    int i, j;
    
    lista2 *head = NULL, *new=NULL;
    lista1 *new2 = NULL;
    
    for(i = 0; i < 5; i++){
        new = (lista2*)malloc(sizeof(lista2));
        new->wsk = head;
        head = new;
        new->var_loc = NULL;
        sprintf(new->typ, "external list, element %d", i);
        for(j = 0; j < 10; j++){
            new2 = (lista1*)malloc(sizeof(lista1));
            new2->wsk = new->var_loc;
            new->var_loc = new2;
            sprintf(new2->add, "internal list, element %d", j);
        }
    }
    
    // Print list contents
    lista2 *p2;
    lista1 *p1;
    
    for(p2 = head; p2; p2=p2->wsk){ // iterate over ext. list
        printf("%s\n", p2->typ);
        for(p1 = p2->var_loc; p1; p1 = p1->wsk){ // iterate over int. list
            printf("  %s\n", p1->add);
        }
    }