#include #include #define SIZE 100 typedef struct tray { char color[ 10 ]; /* its color */ int id; /* its unique id number */ struct tray *below; /* pointer to successor on stack */ } TRAY; TRAY *top = NULL; /* pointer to top TRAY on stack */ int currsize = 0; /* number of items on stack */ void get_data( TRAY *ptr ), put_data( const TRAY *ptr ); TRAY *pop( void ), *push( TRAY tr ); main() { int ans, flag; TRAY t, *ptr; /* do stack operations until user signals halt */ do { do { printf( "\n\n\tEnter 1 to push, 2 to pop: " ); scanf( "%d", &ans ); printf( "\n" ); switch ( ans ) { case 1: /* get a TRAY and add it to stack */ get_data( &t ); if ( push( t ) == NULL ) printf( "\n\nSTACK FULL\n\n" ); break; case 2: /* delete a TRAY from stack and print it */ if ( ( ptr = pop() ) != NULL ) put_data( ptr ); else printf( "\n\nSTACK EMPTY\n\n" ); break; default: printf( "\nIllegal response\n" ); break; } } while ( ans != 1 && ans != 2 ); printf( "\n\n\n1 to continue, 0 to quit: " ); scanf( "%d", &flag ); printf( "\n" ); } while ( flag ); return EXIT_SUCCESS; } /* get_data prompts the user for a TRAY's color and id and stores it at the address passed. */ void get_data( TRAY *ptr ) { printf( "\nenter the tray's color: " ); scanf( "%s", ptr -> color ); printf( "\nenter the tray's id: " ); scanf( "%d", &( ptr -> id ) ); printf( "\n" ); } /* put_data writes the color and id of the TRAY whose address is passed. */ void put_data( const TRAY *ptr ) { printf( "\ntray's color: %s\n", ptr -> color ); printf( "\ntray's id: %d\n", ptr -> id ); } /* If the stack is full, push returns NULL. Otherwise, push allocates storage for a TRAY, copies the data passed into the allocated storage, adds the node to the linked list, updates top and the current size of the stack, and returns the address of the TRAY added. */ TRAY *push( TRAY tr ) { TRAY *ptr; if ( currsize >= SIZE ) /* stack full? */ return NULL; ptr = malloc( sizeof ( TRAY ) ); /* new TRAY */ *ptr = tr; /* store data */ ptr -> below = top; /* push it on stack */ top = ptr; /* update top */ ++currsize; /* update current stack size */ return ptr; } /* If the stack is empty, pop returns NULL. Otherwise, pop copies the top TRAY to permanent storage, updates top, frees the stack storage, updates the current size of the stack, and returns the address of the TRAY. */ TRAY *pop( void ) { static TRAY popped_tray; TRAY *ptr; if ( currsize < 1 ) /* empty stack? */ return NULL; popped_tray = *top; /* copy data to return */ ptr = top; /* save address of 1st node for garbage collection */ top = top -> below; /* update top */ free( ptr ); /* collect garbage */ --currsize; /* update current size */ return &popped_tray; }