Hi,
I created a linked list in C and I would like to print all the elements of this list. But my function doesn't print all the items in the sublist. It's actually prints all the items in the list and only the first item in the sublist, the rest of the sublist is ignored for some reason I don't understand.
For example, in this list, lst = (a (b c) d e),
Code:
char a = 'a', b = 'b', c = 'c', d = 'd', e = 'e';
list lst = NULL;
list sublist = NULL;
// lst = (a (b c) d e)
sublist = cons(&b, cons(&c, NULL));
lst = cons(&a, lcons(sublist, cons(&d, cons(&e, NULL))));
It's only prints (a b d e), or :
Code:
([a|1151641587]->[b|1151641588]->[d|1151641590]->[e|1151641591]->nil)
I would like to print (a (b c) d e).
Here the program :
Code:
#include <stdio.h>
#include <stdlib.h>
#define data(Doublet) ((Doublet)->data)
#define next(Doublet) ((Doublet)->next)
typedef struct Doublet {
void * data ;
struct Doublet *next ;
} * list ;
list cons(void *, const list) ;
list lcons(list lst, list) ;
void print_lst(list L) ;
int main(int argc, char const *argv[]){
char a = 'a', b = 'b', c = 'c', d = 'd', e = 'e';
list lst = NULL;
list sublst = NULL;
// lst = (a (b c) d e)
sublst = cons(&b, cons(&c, NULL));
lst = cons(&a, lcons(sublst, cons(&d, cons(&e, NULL))));
print_lst(lst);
return 0;
}
list cons(void * elt, const list L){
list Cons = malloc(sizeof(struct Doublet)) ;
data(Cons) = elt ; // Cons -> data = elt
next(Cons) = L ; // Cons -> next = L
return Cons ;
}
list lcons(list lst, list L){
list LCons = malloc(sizeof(struct Doublet)) ;
data(LCons) = *(list*)lst ;
next(LCons) = L;
return LCons ;
}
void print_lst(list L){
printf("(");
for(; L; L=next(L)){
if(L->data)
printf("[%c|%d]->", *(char*)L->data, *(int*)&L->data);
else
print_lst(L->next);
}
printf("nil)");
}