Queue using Stacks | CPP program to implement Queue using two stacks with costly enQueue ( ) ; Move all elements from s1 to s2 ; Push item into s1 ; Push everything back to s1 ; Dequeue an item from the queue ; if first stack is empty ; Return top of s1 ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Queue { stack < int > s1 , s2 ; void enQueue ( int x ) { while ( ! s1 . empty ( ) ) { s2 . push ( s1 . top ( ) ) ; s1 . pop ( ) ; } s1 . push ( x ) ; while ( ! s2 . empty ( ) ) { s1 . push ( s2 . top ( ) ) ; s2 . pop ( ) ; } } int deQueue ( ) { if ( s1 . empty ( ) ) { cout << " Q ▁ is ▁ Empty " ; exit ( 0 ) ; } int x = s1 . top ( ) ; s1 . pop ( ) ; return x ; } } ; int main ( ) { Queue q ; q . enQueue ( 1 ) ; q . enQueue ( 2 ) ; q . enQueue ( 3 ) ; cout << q . deQueue ( ) << ' ' ; cout << q . deQueue ( ) << ' ' ; cout << q . deQueue ( ) << ' ' ; return 0 ; }