in DS edited by
16,282 views
41 votes
41 votes

Suppose you are given an implementation of a queue of integers. The operations that can be performed on the queue are:

  1. $isEmpty (Q)$ — returns true if the queue is empty, false otherwise.
  2. $delete (Q)$ — deletes the element at the front of the queue and returns its value.
  3. $insert (Q, i)$ — inserts the integer i at the rear of the queue.

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 above function $f$ ?

  1. Leaves the queue $Q$ unchanged
  2. Reverses the order of the elements in the queue $Q$
  3. 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. Empties the queue $Q$
in DS edited by
16.3k views

4 Comments

I think the program will never come to execute insert(Q, i) operation because the program recurse before it and as it become empty the isEmpty() becomes true and if section becomes false and it should not enter that setion and terminates.

Kindly tell me where I am wrong.
2
2
i also have the same doubt, initially it goes on deleting the elements from the queue and then the loop condition becomes false. So how are we executing the insert(q,i) statement...
1
1
@Anand Mundhe

According to me,

implementing using arrays : call by reference is default.

implementing using linked list : you are sending a pointer of the queue, which is also call by reference.

So I think we don’t have to worry about call by value here
0
0

11 Answers

3 votes
3 votes

Here is traced out recursive tree.

Answer: Option B

0 votes
0 votes
In this recursion, queue is being deleted by one element every time and getting saved in i. And again the function calls itself. When queue becomes empty, the last element will be inserted first in the queue. This will be for all the elements present. Thus, it reverses the order of elements in the queue.
0 votes
0 votes
Storing an element in a recursive function before you recurse is equivalent to storing in a stack, so you are taking elements from a queue and putting them in the stack. When the queue is empty you are inserting them back into the Queue.

This is how you reverse a queue with a stack.

2 Comments

When all the elements are deleted, the if condition will be false and we will be out of the statement so how will the insert(Q,i) statement executes?
1
1
isEmpty will evaluate to true, we are negating it, thus we will exit the last call.
0
0
0 votes
0 votes

This is a recursive program let Queue contians 1,2,3,4  and we can make recursion tree as

Now Traverse this recursion tree 

insert(4) 

  4

insert(3)

   4   3

insert(2)

   4      3   2

insert(1)

    4     3    2    1

So queue got reversed

Answer(b)

by
Answer:

Related questions