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 AR E 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.
https://leetcode.com/problems/implement-stack-using-queues/
Use the queue to simulate the stack. Can only be queued with queue, out of team, length and whether it is empty four functions. That is, the JS array of push (), Shift (), length,length===0. Two queues poured upside down. The stack operation is to find a queue that is not empty. The operation of the stack and the top element of the stack is the same, and the non-empty queue, except for all other elements of the last element, is poured into the other. Whether the stack is empty or two queues are empty.
1 /**2 * @constructor3 */4 varStack =function() {5 This. QueueA = [];6 This. Queueb = [];7 };8 9 /**Ten * @param {number} x One * @returns {void} A */ -Stack.prototype.push =function(x) { - if( This. queuea.length!== 0){ the This. Queuea.push (x); -}Else{ - This. Queueb.push (x); - } + }; - +Stack.prototype.moveAToB =function() { A if( This. queueb.length!== 0){ at varTMP = This. QueueA; - This. QueueA = This. Queueb; - This. Queueb =tmp; - } - varLen = This. queuea.length; - for(vari = 0; i < len-1; i++){ in varQueuepeek = This. Queuea.shift (); - This. Queueb.push (Queuepeek); to } + }; - the /** * * @returns {void} $ */Panax NotoginsengStack.prototype.pop =function() { - This. Moveatob (); the This. Queuea.shift (); + }; A the /** + * @returns {number} - */ $Stack.prototype.top =function() { $ This. Moveatob (); - varStacktop = This. Queuea.shift (); - This. Queueb.push (stacktop); the returnStacktop; - };Wuyi the /** - * @returns {Boolean} Wu */ -Stack.prototype.empty =function() { About if( This. Queuea.length = = 0 && This. Queueb.length = = 0){ $ return true; - } - return false; - };
[Leetcode] [JavaScript] Implement Stack using Queues