Implement the following operations of a queue using stacks.
- Push (x)--push element x to the back of the queue.
- Pop ()--Removes the element from in front of the queue.
- Peek ()--Get the front element.
- Empty ()--Return whether the queue is empty.
Notes:
- Must use onlyStandard operations of a stack – which means only
push to top,peek/pop from top,size, andis emptyOperations is valid.
- Depending on your language, stack may is not supported natively. You could simulate a stack by using a list or deque (double-ended queue), as long as if you have standard operations of a s Tack.
- You may assume this all operations is valid (for example, no pop or peek operations would be called on an empty queue).
Thinking Analysis: This question and a few years ago wrote a story by the blog is the same topic: The interview problem study with two stack simulation implementation of the queue. The basic approach is simple, with two stacks can be simulated a queue, the basic idea is two LIFO = FIFO, element into the queue always into a stack, element out of the queue if the B stack is not empty directly eject the B stack head element; If b stack is empty, put a stack of elements out of the stack and then eject the B stack head, This simulates a queue. The core is to ensure that each element is out of the stack through a A-B two stacks, so that the implementation of two LIFO = FIFO first.
AC Code
Class Myqueue { //Push element x to the back of the queue. stack<integer> Stacka = new stack<integer> (); stack<integer> stackb = new stack<integer> (); public void push (int x) { stacka.push (x); } Removes the element from in front of the queue. public void Pop () { if (!stackb.isempty ()) { stackb.pop () } and else {while (!stacka.isempty ()) { Stackb.push (Stacka.pop ()); } Stackb.pop (); } } Get the front element. public int Peek () { if (!stackb.isempty ()) { return Stackb.peek (), } else {while (!stacka.isempty ( ) { Stackb.push (Stacka.pop ()); } return Stackb.peek (); } } Return whether the queue is empty. public Boolean empty () { return (Stacka.isempty () && stackb.isempty ())} }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode Implement Queue using Stacks