Self-test 18:
Stack and Queue

  1. What policy does stack use when inserting and removing items

    1. LILO
    2. FIFO
    3. LIFO
    Solution
    C


  2. What policy does queue use when inserting and removing items?

    1. LILO
    2. FIFO
    3. LIFO
    Solution
    B


  3. What do we say when we add an item to a stack?

    1. push
    2. add
    3. enqueue
    Solution
    A


  4. What do we say when we delete an item from a queue?

    1. pop
    2. poll
    3. dequeue
    Solution
    C


  5. What is the result of the following program?

    int main(void)
    {
    	int_stack s;
    	int_queue q;
    	int b;
    	s.push(2);
    	s.push(1);
    	q.enqueue(2);
    	q.enqueue(1);
    	b = a.top();
    	a.pop();
    	cout << b << endl;
    	b = a.top();		
    	a.pop();
    	cout << b << endl;
    	b = q.front();		
    	q.dequeue();
    	cout << b << endl;
    	b = q.front();		
    	q.dequeue();
    	cout << b << endl;
    	return 0;
    }
    
    
    Solution
    1
    2
    2
    1


  6. Following the example "Balanced Parentheses" in lecture notes, what are the items in the stack at the time we reach the first "[" when scanning "{ ( ( ) ( ) ( [ ] ) ) }"?

    Solution
    Answer: { ( (


  7. Fill in the blanks in the following block of code that reverse the items in an int_queue q by using a intermediate int_stack s.

    void reverse_queue(int_queue q)
    {
    	int_stack s;
    	while (!q.empty())
    	{
    		int a = q.front();		
    		q.dequeue();
    		s.push(a);
    	}
    	while (________)
    	{
    		______________;
    		______________;
    		______________;
    	}
    }
    
    
    Solution
    void reverse_queue(int_queue q)
    {
    	int_stack s;
    	while (!q.empty())
    	{
    		int a = q.front();		
    		q.dequeue();
    		s.push(a);
    	}
    	while (!s.empty())
    	{
    		int a = s.top();	
    		s.pop();
    		q.enqueue(a);
    	}
    }