Suppose you are given an implementation of a queue of integers. Consider the…

2007

Suppose you are given an implementation of a queue of integers.

Queue operation definitions: isEmpty(Q) reports whether Q is empty; delete(Q) removes and returns the front element; insert(Q, i) inserts i at the rear.

Consider the following function:

void f(queue Q)
{
    int i;
    if (!isEmpty(Q))
    {
        i = delete (Q);
        f(Q);
        insert(Q, i);
    }
}

What operation is performed by the function f?

Answer: B. Reverses the order of the elements in the queue QConcept: In recursion, operations placed after the recursive call execute while the call stack unwinds. Values saved before descending are therefore handled…

  1. A.

    Leaves the queue Q unchanged

  2. B.

    Reverses the order of the elements in the queue Q

  3. C.

    Deletes the element at the front of the queue Q and inserts it at the rear keeping the other elements in the same order

  4. D.

    Empties the queue Q

Attempted by 577 students.

Show answer & explanation

Correct answer: B

Concept: In recursion, operations placed after the recursive call execute while the call stack unwinds. Values saved before descending are therefore handled in last-saved, first-restored order.

For a queue, deleting from the front before recursion and inserting at the rear after recursion changes pairwise order according to that unwinding order.

Application: Trace the calls on a concrete queue [1, 2, 3].

  1. The first call deletes 1 and recursively processes [2, 3].

  2. The next call deletes 2 and recursively processes [3].

  3. The next call deletes 3 and reaches the empty-queue base case.

  4. During unwinding, 3 is inserted first, then 2, then 1, producing [3, 2, 1].

Cross-check: Each of the n elements is deleted once and inserted once, so the time cost is O(n). The recursion depth is n, so the auxiliary stack space is O(n). Applying the same transformation a second time restores the original order.

Result: The function reverses the order of the elements in queue Q.

A video solution is available for this question — log in and enroll to watch it.

Explore the full course: Iocl Engineers Officers Grade A Paper 2

Loading lesson…