How to implement deactivation using two stacks

Dequeue is a double-ended queue: en-queue and de-queue are possible at both ends.

How to define ADT operations for dequeue using 2 stacks.

Implementation must also consider efficiency.

+3
source share
2 answers

the easiest solution would be to use one stack as the head of the queue and one as the tail. Queue operations can be just pushing the corresponding stack, and detection operations will simply pop into the corresponding stack.

, , , , , , . , . , . , , , , .

,

+3

:

enqueue(q,  x)
  1) Push element x to stack1. This very simple, the problem is dequeue

dequeue(q)
  1) If stacks1 and stack2 are empty then error  "UNDERFLOW"
  2) If stack2 is empty, then 
       while (stack1 is not empty) do
           push all element from satck1 to stack2.
        end while;
  3) Pop the element from stack2 and return it.
+1

Source: https://habr.com/ru/post/1628241/


All Articles