#Meta-Wlp: #Macro: TITLE wlp: Learn C (5) p. 13 #Eval: $TITLE$ #Macro: PAGE bb5-13

Linked Lists.

But all along, you have probably been wondering, what about linked lists? Please show me how do implement these remarkable structures?

C allows for incomplete types as fields of a structure if it can predict the size. A pointer is one-size-fits-all. So even if struct node hasn't been fully declared by the time the struct node * field is encountered in the following definition, C allows it.

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

struct node { int value; struct node * next ; } ;

struct node * create( int value, struct node * next ) {
   struct node * sn = (struct node *) malloc(sizeof(struct node)) ;
   sn->value = value ;
   sn->next = next ;
   return sn ;
}

void print( struct node * sn ) {
   while ( sn ) {
     printf("%d\n", sn->value ) ;
     sn = sn->next ;
   }
}

int main( int argc, char * argv[] ) {
    struct node * sn_root = 0 ; /* also sn_root = NULL */
    int i ;
    for ( i=0; i<9; i++ ) sn_root = create( i, sn_root ) ;
    print( sn_root ) ;
}

#Shuffle: none $PAGE$-A $PAGE$-B Return to index. #: That is a very great way to do linked lists. #: I don't ever want to use linked lists. #: