Queue using Stacks | Python3 program to implement Queue using two stacks with costly enQueue ( ) ; Move all elements from s1 to s2 ; Push item into self . s1 ; Push everything back to s1 ; Dequeue an item from the queue ; if first stack is empty ; Return top of self . s1 ; Driver code
class Queue : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . s1 = [ ] NEW_LINE self . s2 = [ ] NEW_LINE DEDENT def enQueue ( self , x ) : NEW_LINE INDENT while len ( self . s1 ) != 0 : NEW_LINE INDENT self . s2 . append ( self . s1 [ - 1 ] ) NEW_LINE self . s1 . pop ( ) NEW_LINE DEDENT self . s1 . append ( x ) NEW_LINE while len ( self . s2 ) != 0 : NEW_LINE INDENT self . s1 . append ( self . s2 [ - 1 ] ) NEW_LINE self . s2 . pop ( ) NEW_LINE DEDENT DEDENT def deQueue ( self ) : NEW_LINE INDENT if len ( self . s1 ) == 0 : NEW_LINE INDENT print ( " Q ▁ is ▁ Empty " ) NEW_LINE DEDENT x = self . s1 [ - 1 ] NEW_LINE self . s1 . pop ( ) NEW_LINE return x NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT q = Queue ( ) NEW_LINE q . enQueue ( 1 ) NEW_LINE q . enQueue ( 2 ) NEW_LINE q . enQueue ( 3 ) NEW_LINE print ( q . deQueue ( ) ) NEW_LINE print ( q . deQueue ( ) ) NEW_LINE print ( q . deQueue ( ) ) NEW_LINE DEDENT