用两个栈实现队列

题目:用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型

思路:

栈1:用于入队列存储

栈2:出队列时将栈1的数据依次出栈,并入栈到栈2中。栈2出栈即栈1的底部数据即队列要出的数据。

注意:栈2为空才能补充栈1的数据,否则会打乱当前的顺序。

代码:

 1 var stack1 = [], stack2=[];
 2 function push(node)
 3 {
 4     // write code here
 5      stack1.push(node);
 6 }
 7 function pop()
 8 {
 9     // write code here
10     if(stack2.length){
11         return stack2.pop();
12     }else{
13         if(stack1.length){
14             var len = stack1.length;
15             for(var i=0;i<len;i++){
16                 stack2.push(stack1.pop());
17             }
18             return stack2.pop()
19         }else{
20              return null
21         }
22          
23     }
24 }
25 module.exports = {
26     push : push,
27     pop : pop
28 };

 

 1 var CQueue = function() {
 2    this.stackA = [];
 3    this.stackB = [];
 4 };
 5 
 6 /** 
 7  * @param {number} value
 8  * @return {void}
 9  */
10 CQueue.prototype.appendTail = function(value) {
11     this.stackA.push(value);
12 };
13 
14 /**
15  * @return {number}
16  */
17 CQueue.prototype.deleteHead = function() {
18  if(this.stackB.length){
19         return this.stackB.pop();
20     }else{
21         while(this.stackA.length){
22             this.stackB.push(this.stackA.pop());
23         }
24         if(!this.stackB.length){
25             return -1;
26         }else{
27             return this.stackB.pop();
28         }
29     }
30 };
31 
32 /**
33  * Your CQueue object will be instantiated and called as such:
34  * var obj = new CQueue()
35  * obj.appendTail(value)
36  * var param_2 = obj.deleteHead()
37  */

 

posted @ 2021-05-23 00:14  icyyyy  阅读(118)  评论(0)    收藏  举报