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).
https://leetcode.com/problems/implement-queue-using-stacks/ 2 stack implementation queue. Stack 1 mainly, stack 2 supplemented. Push operation, the stack 2 all the elements are poured into the stack 1, and then the stack 1 pressure buyers. Pop and peek Operations, if the stack 2 is empty, the stack 1 all the elements are poured into the stack 2, and then the stack 2 out buyers.
1 /**2 * @constructor3 */4 varQueue =function() {5 This. Stack1 = [];6 This. Stack2 = [];7 };8 9 /**Ten * @param {number} x One * @returns {void} A */ -Queue.prototype.push =function(x) { - varLen = This. stack2.length; the while(len--){ - This. Stack1.push ( This. Stack2.pop ()); - } - This. Stack1.push (x); + }; - + /** A * @returns {void} at */ -Queue.prototype.pop =function() { - if( This. Stack2.length = = 0){ - varLen = This. stack1.length; - while(len--){ - This. Stack2.push ( This. Stack1.pop ()); in } - } to return This. Stack2.pop (); + }; - the /** * * @returns {number} $ */Panax NotoginsengQueue.prototype.peek =function() { - if( This. Stack2.length = = 0){ the varLen = This. stack1.length; + while(len--){ A This. Stack2.push ( This. Stack1.pop ()); the } + } - return This. stack2[ This. stack2.length-1]; $ }; $ - /** - * @returns {Boolean} the */ -Queue.prototype.empty =function() {Wuyi if( This. Stack1.length = = 0 && This. Stack2.length = = 0){ the return true; - } Wu return false; -};
[Leetcode] [JavaScript] Implement Queue using Stacks