The Gateway to Computer Science Excellence
First time here? Checkout the FAQ!
+16 votes

Suppose a stack implementation supports, in addition to PUSH and POP, an operation REVERSE, which reverses the order of the elements on the stack.

  1. To implement a queue using the above stack implementation, show how to implement ENQUEUE using a single operation and DEQUEUE using a sequence of $3$ operations.
  2. The following post fix expression, containing single digit operands and arithmetic operators $+$ and $*$, is evaluated using a stack. 
    $5 \ 2 * 3 \ 4 + 5 \ 2 * * +$
    Show the contents of the stack
    1. After evaluating $5 \ 2 * 3 \ 4 +$
    2. After evaluating $5 \ 2 * 3 \ 4 + 5 \ 2$
    3. At the end of evaluation
asked in DS by Veteran (52k points)
edited by | 1.4k views

2 Answers

+25 votes
Best answer
  1. For enqueue push operation is sufficient
    For dequeue operation do the following
    -reverse, pop, reverse
  2. Contents of stack from top to bottom:

          i) $7 \ 10$
         ii) $2 \ 5 \ 7 \ 10$
         ii) $80$

answered by Boss (30.9k points)
edited by
Content of stack at end of evaluation should be empty?
for dequeue it should be reverse and pop are sufficient.


For dequeue reverse and pop are not sufficient because we might have popped only one element and would need to push later on. If we don't restore the order the the elements will be jumbled.


@Mizuki....can you explain with this example..please

For dequeue operation do the following 
-reverse, pop, reverse 


   Consider that the stack initially contains the elements 1,2,3,4 from bottom to top (i.e 4 is at the top)

Consider 2 operations to be performed

1) Dequeue

2) Enqueue(5)

For 1)

We'll have to first reverse the stack. So stack contents 4,3,2,1 from bottom to top.

Next,we'll pop the element. So stack contents 4,3,2.

Now we'll have to reverse the elements,since we want to enqueue in 1 operation(if we dont reverse then 5 will be pushed after 2,but it should be pushed after 4). So stack contents 2,3,4.

Now Enqueue(5) . So stack contents 2,3,4,5 from bottom to top.

Hence, total Dequeue operations =3 and Enqueue operations = 1.

+1 vote

final answer should be 80.

answered by Boss (33.9k points)
edited by

Related questions

Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true
49,535 questions
54,120 answers
71,034 users