Algorithm 4 Stack Implemented using Two Queues

Require: Q1Q_1 and Q2Q_2 are two queues.

Ensure: Implementation of stack operations with Q1Q_1 and Q2Q_2 .

1: // Calculate the number of elements in a queue

2:procedure QueueSize(QQ)

3:if Q.headQ.tailQ.head \le Q.tail then

4:return Q.tailQ.headQ.tail - Q.head

5:end if

6:return Q.length+Q.tailQ.headQ.length + Q.tail - Q.head

7:end procedure

8:

9:Qa=Q1Q_a = Q_1 // the active queue

10:Qi=Q2Q_i = Q_2 // the inactive queue

11: // Swap the active and inactive queue

12:procedure Toggle()

13:tmp=Qatmp = Q_a

14:Qa=QiQ_a = Q_i

15:Qi=tmpQ_i = tmp

16:end procedure

17:

18:procedure Push(xx)

19:Enqueue(Qa,xQ_a, x)

20:end procedure

21:

22:procedure Pop()

23:while QueueSize(QaQ_a) >1>1 do

24:x=x = Dequeue(QaQ_a)

25:Enqueue(Qi,xQ_i, x)

26:end while

27:Toggle()

28:return Dequeue(QiQ_i)

29:end procedure