Topic:
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).
Links: http://leetcode.com/problems/implement-queue-using-stacks/
Exercises
Implement queues with stacks. The previous practice is to use a stack to save all the data, each time you add new data before the Daoteng to another stack, and then Daoteng back, this will be very slow, only defeated 13% of the players ...
Think about it, two stacks, one for push, the other for pop. When two stacks are not empty, push and pop and peek,isempty () are all O (1). But the worst is going to be a long time. In general, you can win with average time. The code can also optimize optimizations.
Time Complexity-push-o (n), Pop-o (n), Peek-o (n), Isempty-o (1).
classMyqueue {PrivateStack<integer> Stack1 =NewStack<>(); PrivateStack<integer> Stack2 =NewStack<>(); //Push element x to the back of the queue. Public voidPushintx) {if(Stack1.isempty ()) {Stack1.push (x); } Else if(Stack2.isempty ()) {Stack2.push (x); while(!stack1.isempty ()) Stack2.push (Stack1.pop ()); } Else{stack1.push (x); } } //Removes the element from in front of the queue. Public voidpop () {if(!Stack2.isempty ()) {Stack2.pop (); } Else if(!Stack1.isempty ()) { while(!stack1.isempty ()) Stack2.push (Stack1.pop ()); Stack2.pop (); } } //Get the front element. Public intPeek () {if(!Stack2.isempty ()) { returnStack2.peek (); } Else if(!Stack1.isempty ()) { while(!stack1.isempty ()) Stack2.push (Stack1.pop ()); returnStack2.peek (); } Else return0; } //Return Whether the queue is empty. Public Booleanempty () {returnStack1.isempty () &&Stack2.isempty (); }}
Reference:
Https://leetcode.com/discuss/44106/short-o-1-amortized-c-java-ruby
Https://leetcode.com/discuss/44124/accepted-0ms-c-solution-with-two-std-stack-easy-understand
Https://leetcode.com/discuss/45146/accepted-clean-java-solution
Https://leetcode.com/discuss/58346/my-java-solution-with-only-editing-the-push-method
Https://leetcode.com/discuss/53948/java-solution-using-two-stacks
Https://leetcode.com/discuss/47278/o-n-3o-1-solution-in-java
Https://leetcode.com/discuss/67154/easy-java-solution-just-edit-push-method
Https://leetcode.com/discuss/62282/my-java-solution-with-2-stacks
232. Implement Queue using Stacks