【剑指Offer】面试题9:用两个栈实现队列——JS实现
2019-04-29 12:45
225 查看
一、用两个栈实现队列
题目描述:
用两个栈来实现一个队列,完成队列的 Push 和 Pop 操作。队列中的元素为 int 类型。
注:
1. 队列 —— 先进先出。
栈 —— 先进后出。
2. push: 在数组的末尾添加元素,并返回新的长度。(改变数组)
pop: 从数组中把最后一个元素删除,并返回这个元素的值。(改变数组)
代码如下:
[code]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: 从数组中把第一个元素删除,并返回这个元素的值。(改变数组)
代码如下:
[code]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
相关文章推荐
- 【剑指offer】2.3.5栈和队列——面试题7:用两个栈实现队列
- 【剑指offer】面试题:两个队列实现栈
- 【剑指offer 面试题7】用两个栈实现队列
- 【剑指Offer学习】【面试题7:用两个栈实现队列】
- 剑指Offer——面试题7:用两个栈实现队列
- 剑指offer面试题7:用两个栈实现队列&用两个队列实现栈
- 【剑指Offer】JS实现两个队列表示一个栈
- 剑指offer-面试题07-衍生题目:用两个队列实现栈
- 剑指Offer面试题7[用两个栈实现队列]
- 剑指offer 面试题7 用两个栈实现队列
- 剑指offer 面试题7 两个栈实现队列
- 【剑指offer】面试题7:用两个栈实现队列
- 剑指Offer面试题7:用两个栈实现队列 Java实现
- 【剑指offer】面试题 9:用两个栈实现队列
- 剑指Offer面试题7用两个栈实现队列(附带用两个队列实现栈)
- 剑指Offer面试题7(Java版):用两个栈实现队列与用两个队列实现栈
- 剑指Offer_面试题07_用两个栈实现队列
- 剑指offer--面试题7:用两个栈实现队列--Java实现
- 【练习笔记】剑指offer-面试题7 :用两个栈实现队列
- 【剑指offer】面试题7:两个栈实现队列