edited by
1,568 views
3 votes
3 votes

Suppose that stacks and queues are provided as opaque data types, offering only operations to add elements, to remove elements, and to test for emptiness. Suppose that a programmer wants to count the number of elements in a given stack or queue $C$, which is currently in some state $t$, using only one auxiliary stack or queue $D$. The structures $C$ and $D$ can be used in any way possible based on the methods they offer, but $C$ must be restored to its state $t$ after counting its elements. Counting elements as described above is possible for which of the following data types?

(1) $C$ is a queue and $D$ is a queue.

(2) $C$ is a stack and $D$ is a stack.

(3) $C$ is a queue and $D$ is a stack.

  1. None
  2. $1$ and $2$ only.
  3. $1$ and $3$ only.
  4. $1$, $2$ and $3$.

edited by

1 Answer

Best answer
3 votes
3 votes

Given a queue and another queue, we can simply dequeue from one and enqueue to another - we get the same order and can get the count. Finally move all elements from D to C by repeating the same procedure.

Given a stack and a stack, we do pop from 1 and push to another. When stack is empty, we get the count and all elements in the new stack are in reverse order. Repeating the procedure from D to C will correct the order.

Given a queue and an auxiliary stack, we can get the count by moving all elements to stack. But when the elements are moved back their order is reversed. But we can again move all elements to stack and then back to queue. So, we get the count and maintain the order.

So, (d) is the answer. 

selected by

Related questions

0 votes
0 votes
1 answer
1
Souvik33 asked Nov 2, 2022
840 views
Which data structure would be most appropriate to implement a collection of values with the following 3 characteristicsSingly link list with head and tail pointerDoubly l...