/* linkList_1.c create, initiailize, print and free a simple Linked Listed of dynamic structs Tim Hoffman 15123 */ #include #include #include typedef struct Node { int data; struct Node *next; } Node; /* Node is now a data type */ void freeList( Node * head ); void printList( Node * head ); void fatal( char * msg ); int main( int argc, char *argv[]) { Node *head = NULL; Node *new; int maxLen; int i; if (argc < 2) fatal("must enter an int >= 0 on cmd line\n"); maxLen = atoi( argv[1]); if (maxLen < 0) fatal("must enter an int >= 0 on cmd line\n"); for (i=0 ; i < maxLen ; ++i ) { new = malloc( sizeof(Node) ); if (!new) fatal("malloc of Node failed"); new->data=i; new->next = head; head = new; } /* print the list */ printList( head ); /* free the list */ freeList( head ); head = NULL; return 0; } /* ----------------------------------------------------------------------------- */ /* use recursion to free string and struct on the way back up the list. Going forward would be cutting our bridge off in front of us */ void freeList( Node * head ) { if (!head) return; freeList( head->next ); /* recurse to the end of list */ free( head ); } /* Notice we use our incoming head pointer as an iterator We are not corrupting the real head in main - this is just a copy! */ void printList( Node * head ) { printf("\nHEAD: "); while ( head ) { printf(" %d ", head->data ); head = head->next; } printf("\n"); } void fatal( char * msg ) { printf("\nFatal Error: %s\n\n", msg ); exit(0); }