剑指offer——用两个栈实现队列(Java)
来源:互联网 发布:广州数控车床编程入门 编辑:程序博客网 时间:2024/06/06 09:43
题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
解题思路
考虑栈和队列的特性,栈为先进后出,队列为先进先出,可以认为栈A提供入队列即push的功能,栈B提供出队列即pop功能。
对于push,直接将数据添加进栈A即可。
对于pop,需要分两种情况考虑:
1)若栈B不为空,则直接弹出栈B的数据。
2)若栈B为空,则先依次弹出栈A的数据,放入栈B中,再弹出栈B的数据。
import java.util.Stack;public class Solution { Stack<Integer> stack1 = new Stack<Integer>(); Stack<Integer> stack2 = new Stack<Integer>(); public void push(int node) { stack1.add(node); } public int pop() { if(!stack2.empty()) return stack2.pop(); else{ while(!stack1.empty()){ stack2.push(stack1.pop()); } return stack2.pop(); } }}
阅读全文
0 0
- 剑指Offer:面试题7——用两个栈实现队列(java实现)
- 剑指offer(java代码)——用两个栈实现队列
- 剑指offer——用两个栈实现队列(Java)
- 《剑指offer》用两个队列实现栈 Java版实现
- 《剑指offer》——用两个栈实现队列
- 《剑指offer》——用两个栈实现队列
- 剑指offer——用两个栈实现队列
- 用两个栈实现队列——剑指offer
- 剑指offer——用两个栈实现队列
- 剑指offer——用两个栈实现队列
- 剑指offer——用两个栈实现队列
- 剑指offer——用两个栈实现队列
- 剑指offer——用两个栈来实现队列
- 剑指offer—用两个栈实现队列
- 《剑指offer》—5、用两个栈实现队列
- 牛客网—剑指offer-用两个栈实现队列
- 牛客网—剑指offer-用两个栈实现队列
- 剑指offer(5)—用两个栈实现队列
- matlab 图像基础学习2
- 阿里、腾讯、百度、华为、京东、搜狗和滴滴最新面试题汇集
- hdfs及NameNode中filesystem设计思想
- WIFI技术-Radio Resource Management
- 语音识别哪家强 讯飞 搜狗 百度 阿里还是腾讯
- 剑指offer——用两个栈实现队列(Java)
- 011 数学期望、方差及方差性质
- net.sf.json.JSONException: Error while setting property=createDate type class java.lang.String
- C++学习笔记--前置、后置操作符
- 欢迎使用CSDN-markdown编辑器
- phpstorm误删除的文件或文档找回方式
- Python函数中输入任意数量参数
- python flask中config配置管理问题
- 写冒泡排序可以排序多个字符串。