in DS recategorized
4,561 views
1 vote
1 vote

Consider the following statements :

$S_{1}$ : A queue can be implemented using two stacks.

$S_{2}$ : A stack can be implemented using two queues.

Which of the following is correct ?

  1. $S_{1}$ is correct and $S_{2}$ is not correct.
  2. $S_{1}$ is not correct and $S_{2}$ is correct.
  3. Both $S_{1}$ and $S_{2}$ are correct.
  4. Both $S_{1}$ and $S_{2}$ are not correct.
in DS recategorized
4.6k views

1 Answer

2 votes
2 votes

Both of the statements are true.Lets understand one by one.In both the cases , we are making enqueue simpler and dequeue operation costlier.

Explanation of statement 1:

Let us have 2 stacks S1 and S2 for  our purpose.For enqueue operation , we simply push in S1.For dequeue operation , we have 2 cases :

a) S2 is not empty : In that case ,we simply pop from this stack.

b) S2 is empty : In that case , first we pop all elements from S1 and push into S2.After pushing all the elements from S1 to S2 we pop the topmost element from S2.

Explanation of statement 2:

For this we take 2 queues , say Qand Q2. Now ,

For push operation of stack , we simply enqueue into that queue which is not empty.

For pop operation , in any case , we do the following :

a) Dequeue all elements from the queue which is non empty and enqueue into the empty queue.

b) Then dequeue the front element from the queue where enqueue has been performed recently.

Hence, both statements S1 and S2 are true.Hence C is the correct option.

3 Comments

@habibkhan, Please check these lines again -

For push operation of stack , we simply enqueue into that queue which is not empty.

For pop operation , in any case , we do the following :

a) Dequeue all elements from the queue which is non empty and enqueue into the empty queue.

b) Then dequeue the front element from the queue where enqueue has been performed recently.

Let us do enqueue - 1, 2, 3, 4, 5

Now in the first line you said that we simply enqueue into that queue which is not empty, in the begning we will aways have an empty quueue .. right ??


Now, In cae of pop, you said that Dequeue all elements from the queue which is non empty and enqueue into the empty queue.

Lets say, q1 contains - 1, 2, 3, 4 and q2 is empty.

After doing the first operation for pop, q2 = 1, 2, 3, 4   and q1 will become empty ... right  ??


Now, In the 2nd operation for pop you said that, Then dequeue the front element from the queue where enqueue has been performed recently, and I think it will return 1 right ?? but it should return 4, because it was the last element which was inserted into the queue in the last push operation ... right ??

0
0
0
0
okay, Thanks @habibkhan :)
0
0

Related questions