/********************************************************************* ** CS228 Spring 1997 ** ** Solutions For Quiz 2 ** *********************************************************************/ // Problem 1. ( 5 Points ) template class Stack { public: Stack(); void push( T item ); T pop(); T top(); bool isEmpty(); bool isFull(); private: T stackArray[ maxStackSize ]; int topIndex; }; // Problem 2. ( 6 Points ) template void Stack::push( T item ) { if ( isFull() ) { // Something like this... cerr << "Stack Full, item: " << item << " not pushed." << endl; } else { stackArray[ ++topIndex ] = item; } return; } // Problem 3. ( 7 Points ) /********************************************************************* Symbol | Postfix Expression | Stack ---------------------------------------------------------------------- 3 | 3 | - | 3 | - 5 | 3 5 | - + | 3 5 - | + 2 | 3 5 - 2 | + + | 3 5 - 2 + | + 11 | 3 5 - 2 + 11 | + * | 3 5 - 2 + 11 | + * ( | 3 5 - 2 + 11 | + * ( 2 | 3 5 - 2 + 11 2 | + * ( - | 3 5 - 2 + 11 2 | + * ( - 1 | 3 5 - 2 + 11 2 1 | + * ( - ) | 3 5 - 2 + 11 2 1 - | + * + | 3 5 - 2 + 11 2 1 - * + | + 4 | 3 5 - 2 + 11 2 1 - * + 4 | + * | 3 5 - 2 + 11 2 1 - * + 4 | + * 6 | 3 5 - 2 + 11 2 1 - * + 4 6 | + * (end) | 3 5 - 2 + 11 2 1 - * + 4 6 * + | *********************************************************************/ // Problem 4. ( 7 Points ) // Assume QueueNode defined as follows: struct QueueNode { QueueNode( int I = 0 ) : data( I ) {} int data; QueueNode * next; }; void Queue::insert( const int & X ) { QueueNode * p, * q; if ( IsEmpty( ) ) { // Queue is Empty front = back = new QueueNode( X ); back->next = NULL; } else { p = q = front; // Complete the code for the else part: // Check if element should go before the front if ( X < frotn->data ) { front = new QueueNode( X ); front->next = p; } else if ( x >= back->data ) // Inserting after the back { back = back->next = new QueueNode( X ); back->next = NULL; } else { // X goes somewhere in the middle // first, find where to insert while ( x >= p->data ) { q = p; p = p->next; } // Then insert q->next = new QueueNode( X ); q->next->next = p; } } // end else return; } // There were other ways to do this problem that are equally correct. // We used simple input test cases of: 2, 15 and 8 into the diagram // listed at the bottom of the quiz to determine if a given solution // would work.