[LeetCode][JavaScript]Implement Stack using Queues

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 backpeek/pop from frontsize, 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} x
11  * @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 };

 

 

 
 
 
 
 
posted @ 2015-06-13 00:23  `Liok  阅读(512)  评论(0编辑  收藏  举报