標籤:
Implement Queue using Stacks
Implement the following operations of a queue using stacks.
- push(x) -- Push element x to the back of queue.
- pop() -- Removes the element from in front of 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 are valid.
- Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
- You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).
https://leetcode.com/problems/implement-queue-using-stacks/ 2個棧實現隊列。棧1為主,棧2為輔。push操作,先把棧2所有的元素都倒入棧1,然後對棧1壓桟。pop和peek操作,如果棧2為空白,就把棧1所有元素都倒入棧2,然後對棧2出桟。
1 /** 2 * @constructor 3 */ 4 var Queue = function() { 5 this.stack1 = []; 6 this.stack2 = []; 7 }; 8 9 /**10 * @param {number} x11 * @returns {void}12 */13 Queue.prototype.push = function(x) {14 var len = this.stack2.length;15 while(len--){16 this.stack1.push(this.stack2.pop());17 }18 this.stack1.push(x);19 };20 21 /**22 * @returns {void}23 */24 Queue.prototype.pop = function() {25 if(this.stack2.length === 0){26 var len = this.stack1.length;27 while(len--){28 this.stack2.push(this.stack1.pop());29 }30 }31 return this.stack2.pop();32 };33 34 /**35 * @returns {number}36 */37 Queue.prototype.peek = function() {38 if(this.stack2.length === 0){39 var len = this.stack1.length;40 while(len--){41 this.stack2.push(this.stack1.pop());42 }43 }44 return this.stack2[this.stack2.length - 1];45 };46 47 /**48 * @returns {boolean}49 */50 Queue.prototype.empty = function() {51 if(this.stack1.length === 0 && this.stack2.length === 0){52 return true;53 }54 return false;55 };
[LeetCode][JavaScript]Implement Queue using Stacks