標籤:
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 use only standard operations of a queue -- which means only
push to back, peek/pop from front, size, and is empty operations are valid.
- Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
- You may assume that all operations are valid (for example, no pop or top operations will 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/
用隊列類比棧。只能用隊列的入隊,出隊,長度和是否為空白四個功能。也就是js數組的push(),shift(),length,length===0。 兩個隊列倒來倒去。入棧操作就是找到不為空白的隊列,入隊。出棧和查看棧頂元素的操作是一樣的,把不為空白的那個隊列,除了最後一個元素的其他所有元素都倒到另一個裡去。棧是否為空白就是兩個隊列是否都為空白。
1 /** 2 * @constructor 3 */ 4 var Stack = function() { 5 this.queueA = []; 6 this.queueB = []; 7 }; 8 9 /**10 * @param {number} x11 * @returns {void}12 */13 Stack.prototype.push = function(x) {14 if(this.queueA.length !== 0){15 this.queueA.push(x);16 }else{17 this.queueB.push(x);18 }19 };20 21 Stack.prototype.moveAToB = function() {22 if(this.queueB.length !== 0){23 var tmp = this.queueA;24 this.queueA = this.queueB;25 this.queueB = tmp;26 }27 var len = this.queueA.length;28 for(var i = 0; i < len - 1; i++){29 var queuePeek = this.queueA.shift();30 this.queueB.push(queuePeek);31 }32 };33 34 /**35 * @returns {void}36 */37 Stack.prototype.pop = function() {38 this.moveAToB();39 this.queueA.shift();40 };41 42 /**43 * @returns {number}44 */45 Stack.prototype.top = function() {46 this.moveAToB();47 var stackTop = this.queueA.shift();48 this.queueB.push(stackTop);49 return stackTop;50 };51 52 /**53 * @returns {boolean}54 */55 Stack.prototype.empty = function() {56 if(this.queueA.length === 0 && this.queueB.length === 0){57 return true;58 }59 return false;60 };
[LeetCode][JavaScript]Implement Stack using Queues