#include #include #define SIZE 100 typedef struct tray { char color[ 10 ]; /* its color */ int id; /* its unique id number */ } TRAY; TRAY *trays[ SIZE ]; /* array to hold up to SIZE pointers to TRAY */ int top = -1; /* index into trays */ 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, pushes a pointer to the TRAY onto the stack, and returns the address of the TRAY added. */ TRAY *push( TRAY tr ) { TRAY *ptr; if ( top >= SIZE - 1 ) /* stack full? */ return NULL; ptr = malloc( sizeof ( TRAY ) ); /* new TRAY */ *ptr = tr; /* store data */ trays[ ++top ] = ptr; /* push it and update top */ return ptr; } /* If the stack is empty, pop returns NULL. Otherwise, pop copies the top TRAY to permanent storage, frees the stack storage, updates top, and returns the address of the TRAY. */ TRAY *pop( void ) { static TRAY popped_tray; if ( top < 0 ) /* empty stack? */ return NULL; popped_tray = *trays[ top ]; /* copy top TRAY */ free( trays[ top-- ] ); /* collect garbage */ return &popped_tray; }