标签:
Implement the following operations of a queue using stacks.
push to top
, peek/pop from top
, size
, and is empty
operations are valid.1 /** 2 * @constructor 3 */ 4 var Queue = function() { 5 this.stack1 = []; 6 this.stack2 = []; 7 }; 8 9 /** 10 * @param {number} x 11 * @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
标签:
原文地址:http://www.cnblogs.com/Liok3187/p/4628985.html