We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Queue using Two Stacks
Queue using Two Stacks
Sort by
recency
|
515 Discussions
|
Please Login in order to post a comment
Approach: * take 2 stacks one for enque and another for deque. * if operation is enqueue simply push to first stack * if operation is dequeue - check if there are elements in 2nd stack if not copy all elements from 1st stack and pop the top. Otherwise simply pop 2nd stack top * if operation is front - follow above step instead of popping print the top.
Gist is: stack 2 will have a top element to pop or print. We only copy stack 1 elements into stack 2 when it is empty.
python solution:
Optimal pseudocode, if you resolved it but couple tests giving timout exception then, rewrite this to your preffered programming language:
Python 3 solution:
C solution: