#include // integer linked lists: typedef struct cell * cellp; struct cell { int head; struct cell * tail; }; // constructor: struct cell* cons(int h, struct cell* t) { struct cell * thiscell; thiscell = (struct cell*)malloc(sizeof(struct cell)); thiscell->head = h; thiscell->tail = t; return thiscell; } // accessors: int car(cellp l) { if (l!=NULL) return l->head; else { printf("error\n"); return 0; } } struct cell* cdr(cellp l) { if (l!=NULL) return l->tail; else return NULL; } // cons(2,cons(4,cons(6,NULL))); int length(struct cell* l) { struct cell* i; int ax = 0; // accumulator for(i=l;i!=NULL;i=cdr(i)) ax++; return ax; } // returns nth cell, 0th is first. struct cell* nth(struct cell* l, int n) { if (n<1) return l; else return nth(cdr(l),n-1); } // return last cell struct cell* last(struct cell* l) { struct cell* i = l; if (i==NULL) return NULL; while(cdr(l) != NULL) i = cdr(i); return i; } void printlist(cellp l) { if (l==NULL) printf("\n"); else { printf("%d ",car(l)); printlist(cdr(l)); } } int main() { cellp A; cellp B; cellp C; A = cons(1,cons(3,cons(5,cons(7,NULL)))); B = cons(2,cons(4,cons(6,cons(8,NULL)))); C = cons(car(A),cdr(B)); // C now shares structure with B // if B is deallocated here, C will be destroyed too! // A = cons(0,A); printlist(A); printf("%d\n",length(B)); exit(0); }