剑指offer-两个队列实现栈
2019-07-29 13:38
162 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_20667511/article/details/97632412
题目要求
两个队列实现一个栈的操作
思路
1.假设先入栈a,b,c。(那么a在栈底,c在栈顶),出栈两次操作,得到c,b,(此时栈中还有一个a),之后在入栈d,(此时栈中栈顶是d,栈底是a)在出栈d,栈中还有a。
2.假设队列 queue1 和 queue2 用来模拟栈操作
3.先往队列queue1中入队a,b,c。出栈操作,如果queue1中的队列长度为1,那么直接出队列,否则的话,先将queue1中的数据出队列,然后入队列到queue2中,queue1中仅剩一个元素,此时出队列,即可得到栈顶的元素c,(当queue1出队列完成之后,需要将queue2中的队列中的元素出队列然后入队列queue1)重复操作,出栈b。此时queue1中仅有一个元素a
4.(先入栈d),先将d入队列queue1,此时队列中的元素是a,d,此时出栈的话,将queue1中的a先出队列到queue2中,此时queue1仅剩d,此时d出队列,queue1为空,然后队列queue2出队列入queue1.此时queue1还剩a。d出栈成功
package com.offer.test; import java.util.LinkedList; import java.util.Queue; /** * 两个队列实现栈的功能 * @author zhouwenchen@021.com * @date 2019年6月13日 下午7:40:42 */ public class StackWithTwoQueues { private static Queue<Object> queue1 = new LinkedList<Object>(); private static Queue<Object> queue2 = new LinkedList<Object>(); /** * 栈中添加元素 */ public static void push(Object obj){ queue1.add(obj); } /** * 栈中弹出元素 */ public static Object pop(){ Object obj = null; if(!queue1.isEmpty()){ // 将queue1中的数据,仅保留一个。其他都顺序出队到queue2中 while(queue1.size()>1){ queue2.add(queue1.poll()); } if(queue1.size() == 1){ obj = queue1.poll(); } // 将queue2中的值添加到queue1中 while(!queue2.isEmpty()){ queue1.add(queue2.poll()); } } return obj; } public static void main(String[] args) { push(1); push(2); push(3); System.out.println(pop()); System.out.println(pop()); System.out.println(pop()); System.out.println(pop()); } }
相关文章推荐
- 【剑指offer】用两个栈实现队列
- 剑指offer7——两个栈实现队列
- 剑指 offer:用两个栈实现队列
- 剑指offer--面试题9:用两个栈实现队列
- 【剑指offer】 面试题9 用两个栈实现队列
- 剑指Offer学习总结-用两个栈实现队列
- 【剑指offer】面试题 9:用两个栈实现队列
- 剑指offer-用两个栈实现队列
- 剑指Offer--007-用两个栈实现队列
- 面试题-剑指offer-两个队列实现栈
- 【剑指Offer】两个栈实现一个队列
- [剑指Offer]9.用两个栈实现队列
- 剑指Offer(五)用两个栈实现队列
- 剑指Offer------用两个栈实现队列(用两个队列实现栈)
- 剑指offer之用两个栈实现队列
- 剑指offer:用两个栈实现队列(栈和队列)
- 剑指Offer-【面试题07:两个栈实现队列】
- 牛客网 - 剑指Offer - 考点:栈和队列 题目:用两个栈实现队列
- 剑指offer 用两个栈实现队列
- 剑指Offer:两个栈实现队列