用两个栈实现队列
来源:互联网 发布:sql2000数据库卸载 编辑:程序博客网 时间:2024/06/07 23:26
题目:用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
/***思路:入队直接用stack1存储,出队需要满足先进先出,因此需要再用一个*stack2将stack1中的内容输出*/Stack<Integer> stack1 = new Stack<Integer>(); Stack<Integer> stack2 = new Stack<Integer>(); public void push(int node){ stack1.push(node); } public int pop(){ if(stack1.isEmpty()&&stack2.isEmpty()) throw new RuntimeException("Queue is empty"); if(stack2.isEmpty()){ while(!stack1.isEmpty()){ stack2.push(stack1.pop()); } } return stack2.pop(); }
包含测试用例的完整代码如下:
package stackAndQue;import java.util.Stack;/** * 用两个栈来实现一个队列,完成队列的Push和Pop操作。队列中的元素为int类型 * @author NST_Xx * 思路: */public class Solution { public static void main(String[] args) { Solution s = new Solution(); s.push(1); s.push(2); s.push(3); s.push(4); s.pop(); } Stack<Integer> stack1 = new Stack<Integer>(); Stack<Integer> stack2 = new Stack<Integer>(); public void push(int node){ stack1.push(node); } public int pop(){ if(stack1.isEmpty()&&stack2.isEmpty()) throw new RuntimeException("Queue is empty"); if(stack2.isEmpty()){ while(!stack1.isEmpty()){ stack2.push(stack1.pop()); } } return stack2.pop(); }}
结果:
1
总结:这道题考察栈和队列的性质。
0 0
- 用两个栈实现队列 & 用两个队列实现栈
- 用两个队列实现栈&用两个栈实现队列
- 用两个栈实现队列 & 两个队列实现一个栈
- 两个栈实现队列&&用两个队列实现一个栈
- 用两个栈实现队列 & 两个队列实现栈
- 用两个栈实现队列
- 用两个栈实现队列
- 用两个栈实现队列
- 用两个队列实现栈
- 用两个栈实现队列
- 用两个栈实现队列
- 用两个队列实现栈
- 用两个栈实现队列
- 用两个队列实现栈
- 用两个栈实现队列
- 用两个栈实现队列
- 用两个栈实现队列
- 用两个栈实现队列
- 使用Git向Github上提交代码(Android)
- 微信小程序 的文字复制功能
- Jersey上传文件 @FormDataParam("file") null
- Dom解析xml
- Android系统默认Home应用程序(Launcher)的启动过程源代码分析
- 用两个栈实现队列
- 电子表格数据导入数据库和数据库下载数据到excel PHP代码phpexecl
- Linux修改Shell命令提示符及颜色
- Valgrind使用
- 经典排序——插入排序——C语言版
- cordova 插件 禁止手机横屏
- 开启MySQL远程连接设置
- 河南省第 10 届 ACM 竞赛总结(附榜单)
- PySpider框架安装配置