【剑指Offer】面试题9:用两个栈实现队列——JS实现

一、用两个栈实现队列

题目描述:

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

注:

1. 队列 —— 先进先出。

    栈 —— 先进后出。

2. push: 在数组的末尾添加元素,并返回新的长度。(改变数组)

    pop: 从数组中把最后一个元素删除,并返回这个元素的值。(改变数组)

代码如下:

var stack1=[],stack2=[];
function push(n){
    stack1.push(n);
}
function pop(){
    if(stack2.length===0){
        if(stack1.length===0){
            return null;
        }else{
            var len = stack1.length;
            for(var i=0;i<len;i++){
                stack2.push(stack1.pop());
            }
            return stack2.pop();
        }
    }else{
        return stack2.pop();
    }
}

// 测试
push(1);  // stack1:[1]
push(2);  // stack1:[1,2]
push(3);  // stack1:[1,2,3]
console.log(pop());  //stack1:[] stack2:[3,2] 输出1
console.log(pop());  //stack1:[] stack2:[3]   输出2
push(4);  // stack1:[4]
push(5);  // stack1:[4,5]
console.log(pop());  //stack1:[4,5] stack2:[] 输出3
console.log(pop());  //stack1:[]    stack2:[5,4] 输出4
console.log(pop());  //stack1:[]    stack2:[] 输出5

二、用两个队列实现栈

题目描述:

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

注:push: 在数组的末尾添加元素,并返回新的长度。(改变数组)

       shift: 从数组中把第一个元素删除,并返回这个元素的值。(改变数组)

代码如下:

var queue1=[],queue2=[];
function push(n){
    queue1.push(n);
}
function pop(){
    // 当两个队列均为空时,返回null
    if(queue1.length===0 && queue2.length===0){
        return null;
    }
    // 当队列1为空时,从队列2中依次删除元素(除了最后一个元素),并插入队列1中,再从队列2中弹出最后一个元素。        
    if(queue1.length===0){
        var len = queue2.length;
        for(var i=0;i<len-1;i++){
            queue1.push(queue2.shift());
        }
        return queue2.shift();
    }else{  // 当队列1不为空时,从队列1中依次删除元素(除了最后一个元素),并插入队列2中,再从队列1中弹出最后一个元素。
        var len = queue1.length;
        for(var i=0;i<len-1;i++){
            queue2.push(queue1.shift());
        }
        return queue1.shift();
    }  
}

// 测试
push(1);  // queue1:[1]
push(2);  // queue1:[1,2]
push(3);  // queue1:[1,2,3]
console.log(pop());  //queue1:[]  queue2:[1,2] 输出3
console.log(pop());  //queue1:[1] queue2:[]    输出2
push(4);  // queue1:[1,4]
push(5);  // queue1:[1,4,5]
console.log(pop());  //queue1:[]    queue2:[1,4] 输出5
console.log(pop());  //queue1:[1]   queue2:[]    输出4
console.log(pop());  //queue1:[]    queue2:[]    输出1

END

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值