[LeetCode][JavaScript]Implement Queue using Stacks

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 toppeek/pop from topsize, 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).
 
 
 

 
 
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} 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 };

 

 
posted @ 2015-07-08 00:55  `Liok  阅读(472)  评论(0编辑  收藏  举报