用两个栈实现队列和用两个队列实现栈
来源:互联网 发布:空调的选购 知乎 编辑:程序博客网 时间:2024/06/07 02:13
题目:用两个栈实现一个队列。实现它的两个函数appendTail和deleteHead,分别完成队列尾部插入节点和在队列头部删除节点的功能。
下面是java代码:
package Stackqueue;import java.util.Stack;public class QueueWithTwoStacks {private Stack<Integer> stack1;private Stack<Integer> stack2;public QueueWithTwoStacks() {this.stack1 = new Stack<Integer>();this.stack2 = new Stack<Integer>();}public void appendTail(int[] a) {for (int i = 0; i < a.length; i++) {stack1.push(a[i]);}}public int deleteHead() {while (!stack1.isEmpty()) {int data = stack1.pop();stack2.push(data);}int number = stack2.pop();return number;}public static void main(String[] args) {int a[] = { 1, 2, 3, 4, 5, 6 };QueueWithTwoStacks queueWithTwoStacks = new QueueWithTwoStacks();queueWithTwoStacks.appendTail(a);System.out.println(queueWithTwoStacks.deleteHead());}}
题目:用两个队列实现栈的功能,即pop函数和push函数
java代码:
package Stackqueue;import java.util.LinkedList;import java.util.Queue;public class StackWithTowQueue {private Queue<Integer> queue1;private Queue<Integer> queue2;public StackWithTowQueue() {this.queue1 = new LinkedList<Integer>();this.queue2 = new LinkedList<Integer>();}public void push(int vaule) {//if (queue1.size() == 0 && queue2.size() == 0)queue1.add(vaule);if (queue1.size() != 0) {queue1.add(vaule);} else if (queue2.size() != 0) {queue2.add(vaule);}}public int pop() {if (queue1.size() == 0 && queue2.size() == 0)return 0;int re = 0;if (queue1.size() != 0 && queue2.size() == 0) {while (queue1.size() > 1) {re = queue1.remove();queue2.add(re);}re = queue1.remove();} else if (queue2.size() != 0 && queue1.size() == 0) {while (queue2.size() > 1) {re = queue2.remove();queue1.add(re);}re = queue2.remove();}return re;}public static void main(String[] args) {int a[] = { 1, 2, 3 };StackWithTowQueue stackWithTowQueue = new StackWithTowQueue();for (int i = 0; i < a.length; i++) {stackWithTowQueue.push(a[i]);}for (int i = 0; i < a.length; i++) {System.out.println(stackWithTowQueue.pop());}}}
0 0
- 用两个栈实现队列 & 用两个队列实现栈
- 用两个队列实现栈&用两个栈实现队列
- 用两个栈实现队列 & 两个队列实现一个栈
- 两个栈实现队列&&用两个队列实现一个栈
- 用两个栈实现队列 & 两个队列实现栈
- 用两个栈实现队列
- 用两个栈实现队列
- 用两个栈实现队列
- 用两个队列实现栈
- 用两个栈实现队列
- 用两个栈实现队列
- 用两个队列实现栈
- 用两个栈实现队列
- 用两个队列实现栈
- 用两个栈实现队列
- 用两个栈实现队列
- 用两个栈实现队列
- 用两个栈实现队列
- ArrayIndexOutofBound AbsListView$RecycleBin.addScrapView
- xib---拖拽的方法搭建视图
- ThinkPHP中利用SESSION实现用户登录验证的方法
- (7.2.5)细说SQL Server中的加密
- Notepad++ 快捷键 大全 官方整理过来的
- 用两个栈实现队列和用两个队列实现栈
- 项目上架前,最要注意的问题
- 上传文件前先预览图片的实现方法
- WebView中实现下载DownloadManager
- scrapy在windows下安装
- Objective-C 语法修饰符 static extern const
- [git]创建分支(branch)以测试或添加新特性
- 欧拉路径与欧拉回路
- 一、初用Eclipse体验