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:
- You must use only standard operations of a stack--which means only
push to top
, peek/pop from top
, size
, and is empty
operations AR E 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).
Ideas:
Using two stacks, each time the operation of the queue, the elements of a stack are ejected, and then in the stack of elements pressed into the queue element, then the stack of all the elements popped, press back to the first stack.
Solution:
1 ImportJava.util.Stack;2 3 Public classMyqueue4 {5 PrivateStack<integer>Inputstack;6 PrivateStack<integer>Outputstack;7 8 Publicmyqueue ()9 {TenInputstack =NewStack<>(); OneOutputstack =NewStack<>(); A } - - Public voidPushintx) the { - while(!outputstack.isempty ()) - Inputstack.push (Outputstack.pop ()); - Inputstack.push (x); + while(!inputstack.isempty ()) - Outputstack.push (Inputstack.pop ()); + } A at Public voidpop () - {Outputstack.pop ();} - - Public intPeek () -{returnOutputstack.peek ();} - in Public Booleanempty () -{returnoutputstack.isempty ();} to}
Leetcode 232 Implement Queue using Stacks