GATE CSE
First time here? Checkout the FAQ!
x
+2 votes
131 views

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$.

 

 

asked in DS by Junior (787 points)  
edited by | 131 views

1 Answer

+2 votes
Best answer

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. 

answered by Veteran (273k points)  
selected by
sir,your explanation is perfectly right!

but i have a doubt though there is no need of reversing stack again..as we are interested in counting the number of element...but if we reverse it...den will the state be the same?
This is for which case? 2 or 3?
sir,dere is no scope of confusion in case 1,

and in case 2 and case 3 i am okk with steps,but i have confusion in state!what it actually mean?
State here just means, the order of elements must be the same after we finish the operation.
Top Users Jan 2017
  1. Debashish Deka

    7508 Points

  2. Habibkhan

    4716 Points

  3. Vijay Thakur

    4368 Points

  4. sudsho

    4316 Points

  5. saurabh rai

    4170 Points

  6. santhoshdevulapally

    3436 Points

  7. Arjun

    3432 Points

  8. Bikram

    3240 Points

  9. GateSet

    3202 Points

  10. Sushant Gokhale

    3042 Points

Monthly Topper: Rs. 500 gift card

18,898 questions
23,865 answers
51,932 comments
20,186 users