/* Cons.c, ~comp210/Labs/lab14/Cons.c. * 96.Dec.02, Ian Barland * A sample program for implementing lists in C. */ #include // for NULL #include // Define the structure struct Cons { int car; Cons* cdr; }; /* makeCons * create a list with desired car and cdr */ Cons* makeCons( int datum, Cons* rest ) { Cons* result; // This is the value we'll return. result = new Cons; // Create the new structure (with garbage contents). result->car = datum; // Set up the innards of the structure. result->cdr = rest; return result; } /* printWoParens * Print the elements of a list seperated by a space (only). * Intended as a helper to print(). */ void printWoParens( Cons* l ) { if (l == NULL) return; else { cout << " " << l->car; printWoParens( l->cdr ); } } /* print * print a list with surrounding parentheses. */ void print( Cons* l ) { cout << "("; printWoParens( l ); cout << ")"; } /* numsDown( n ) * Return a list with integers n..1, in that order. */ Cons* numsDown( int n ) { if (n == 0) return NULL; else return makeCons( n, numsDown( n-1 )); } /* length * Given a list, return its length. */ int length( Cons* l ) { //--- you complete this function! --- return -99; } /* main * Just run some test cases. */ int main() { Cons* l1; Cons* l2; Cons* l3; l1 = NULL; l2 = makeCons( 3, makeCons( 5, makeCons( 4, NULL ))); l3 = numsDown( 10 ); l3 = makeCons( 17, l3->cdr ); cout << "l1 is: "; print( l1 ); cout << ", with length " << length( l1 ) << "." << endl; cout << "l2 is: "; print( l2 ); cout << ", with length " << length( l2 ) << "." << endl; cout << "l3 is: "; print( l3 ); cout << ", with length " << length( l3 ) << "." << endl; return 0; }