/* linkList_2.c Tim Hoffman 15-123 create, initiailize, print and free a simple Linked Listed of dynamic structs differs from linkedList_1 in that we pass head's addy into insertAtFront function */ #include #include #include typedef struct Node { int data; struct Node *next; } Node; /* Node is now a data type */ void insertAtFront( Node ** head, int data ); void freeList( Node * head ); void printList( Node * head ); void fatal( char * msg ); int main( int argc, char *argv[]) { Node *head = NULL; 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 ) { insertAtFront( &head, i ); } /* print the list */ printList( head ); /* free the list */ freeList( head ); head = NULL; return 0; } /* mallocs a new Node and links it into front of List node the code in here is taken from the main in linkedList_1 except in this function there is a star before variable head everywhere because head in here is the address of main's head */ void insertAtFront( Node ** head, int data ) { Node * new = malloc( sizeof(Node) ); if (!new) fatal("malloc of Node failed"); new->data=data; new->next = *head; *head = new; } /* ----------------------------------------------------------------------------- */ /* 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 ) { while (head)removeAtFront(&head); /* caller should put a NULL in the head pointer now that list is gone */ } /* 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); }