232. Implement Queue using Stacks
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).
Stack Design
classMyqueue {Deque<Integer> stack =NewArraydeque<integer>(); //Push element x to the back of the queue. Public voidPushintx) {//Organize at push stage becasue peek needs to see the top.deque<integer> temp =NewArraydeque<integer>(); while(!Stack.isempty ()) {Temp.push (Stack.pop ()); } stack.push (x); while(!Temp.isempty ()) {Stack.push (Temp.pop ()); } } //Removes the element from in front of the queue. Public voidpop () {stack.pop (); } //Get the front element. Public intPeek () {returnStack.peek (); } //Return Whether the queue is empty. Public Booleanempty () {returnStack.isempty (); }}
225. Implement Stack using Queues
Implement the following operations of a stack using queues.
- Push (x)-push element x onto stack.
- Pop ()--Removes the element on top of the stack.
- Top ()--Get the top element.
- Empty ()--Return whether the stack is empty.
Notes:
- You must the only standard operations of a queue – which means only
push to back
,, peek/pop from front
size
, and is empty
operations is Valid.
- Depending on your language, queue May is not supported natively. You could simulate a queue by using a list or deque (double-ended queue), as long as if you have standard operations of a Q Ueue.
- You may assume this all operations is valid (for example, no pop or top operations would be called on an empty stack).
Update (2015-06-11):
The class name of the Java function had been updated to Mystack instead of Stack.
Stack Design
classMystack {Deque<Integer> queue =NewArraydeque<integer>(); //Push element x onto stack. Public voidPushintx) {queue.add (x); for(intI=0;i<queue.size () -1;i++) {Queue.add (Queue.poll ()); } } //removes the element on top of the stack. Public voidpop () {queue.poll (); } //Get the top element. Public intTop () {returnQueue.peek (); } //Return Whether the stack is empty. Public Booleanempty () {returnQueue.isempty (); }}
232. Implement Queue using Stacks && 225. Implement Stack using Queues