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).
Train of thought: two stacks to achieve
classMyqueue {Stack<Integer> stack1=NewStack<integer> ();//MasterStack<integer> stack2=NewStack<integer> ();//Auxiliary//Push element x to the back of the queue. Public voidPushintx) {stack1.push (x); } //Removes the element from in front of the queue. Public voidpop () { while(!Stack1.isempty ()) {Stack2.push (Stack1.pop ()); } if(!stack2.isempty ()) Stack2.pop (); while(!Stack2.isempty ()) {Stack1.push (Stack2.pop ()); } } //Get the front element. Public intPeek () {intRet=0; while(!Stack1.isempty ()) {Stack2.push (Stack1.pop ()); } if(!Stack2.isempty ()) {ret=Stack2.peek (); } while(!Stack2.isempty ()) {Stack1.push (Stack2.pop ()); } returnret; } //Return Whether the queue is empty. Public Booleanempty () {returnStack1.isempty (); }}
Each pop and peek operation here will be stack1 to Stack2, which is more troublesome. Think about it can not be sent around, Stack1 can be used as the tail of the team, Stack2 can be used as the first
classMyqueue {Stack<Integer> stack1=NewStack<integer> ();//MasterStack<integer> stack2=NewStack<integer> ();//Auxiliary//Push element x to the back of the queue. Public voidPushintx) {stack1.push (x); } //Removes the element from in front of the queue. Public voidpop () {if(!stack2.isempty ()) Stack2.pop (); Else { while(!Stack1.isempty ()) {Stack2.push (Stack1.pop ()); } if(!stack2.isempty ()) Stack2.pop (); } } //Get the front element. Public intPeek () {intRet=0; if(!stack2.isempty ()) ret=Stack2.peek (); Else { while(!Stack1.isempty ()) {Stack2.push (Stack1.pop ()); } if(!stack2.isempty ()) ret=Stack2.peek (); } returnret; } //Return Whether the queue is empty. Public Booleanempty () {returnStack1.isempty () &&Stack2.isempty (); }}
[Leetcode] Implement Queue using Stacks