JavaShowAlgorithm-使用2个队列实现栈
2017-11-19 19:40
507 查看
队列是先进先出,而栈是先进后出;
考虑到我们取栈顶元素的便利性,我们在实现时使得栈顶等于队列头;
由于栈的pop弹出栈顶元素,而队列的pop也是弹出栈顶元素,所以我们需要特别处理的是插入操作。
由于往栈中添加元素相当于往队列头添加元素,因此我们需要在两个队列中进行元素的转移,比较简单的实现是:
1.q1和q2在任一时刻至少有一个为空,即如果有元素,所以元素只在同一个队列中。
2.当有元素需要插入时,将插入的元素插入到空的队列中,并将另一非空队列的元素转移到该队列中,于是插入的元素添加到了队列头中。
2. 当然,可以换一种思路,把队列尾与栈顶对应起来,这样子需要特别处理的是pop操作以及top操作,相比起来,本文的做法更加简便,因为只需要对插入操作特别处理)
第二种方法具体实现如下:
public class Queue2Stack {
private ArrayQueue queue1;
private ArrayQueue queue2;
private int maxLength;
public Queue2Stack(int capacity) {
maxLength = capacity;
queue1 = new ArrayQueue(capacity);
queue2 = new ArrayQueue(capacity);
}
/**
* 入栈
* @param item
* @return 入栈结果
*/
public boolean push(int item) {
if (size() == maxLength) {
return false;
}
if (queue2.isEmpty()) {
queue1.put(item);
} else {
queue2.put(item);
}
return true;
}
/**
* 出栈
* @return
*/
public Object pop() {
if (size() == 0) {
throw new IndexOutOfBoundsException("栈里已经空啦");
} else {
if (queue2.isEmpty()) {
while (queue1.size() > 1) {
queue2.put(queue1.poll());
}
return queue1.poll();
} else {
while (queue2.size() > 1) {
queue1.put(queue2.poll());
}
return queue2.poll();
}
}
}
public int size() {
return queue1.size() + queue2.size();
}
}
考虑到我们取栈顶元素的便利性,我们在实现时使得栈顶等于队列头;
由于栈的pop弹出栈顶元素,而队列的pop也是弹出栈顶元素,所以我们需要特别处理的是插入操作。
由于往栈中添加元素相当于往队列头添加元素,因此我们需要在两个队列中进行元素的转移,比较简单的实现是:
1.q1和q2在任一时刻至少有一个为空,即如果有元素,所以元素只在同一个队列中。
2.当有元素需要插入时,将插入的元素插入到空的队列中,并将另一非空队列的元素转移到该队列中,于是插入的元素添加到了队列头中。
2. 当然,可以换一种思路,把队列尾与栈顶对应起来,这样子需要特别处理的是pop操作以及top操作,相比起来,本文的做法更加简便,因为只需要对插入操作特别处理)
第二种方法具体实现如下:
public class Queue2Stack {
private ArrayQueue queue1;
private ArrayQueue queue2;
private int maxLength;
public Queue2Stack(int capacity) {
maxLength = capacity;
queue1 = new ArrayQueue(capacity);
queue2 = new ArrayQueue(capacity);
}
/**
* 入栈
* @param item
* @return 入栈结果
*/
public boolean push(int item) {
if (size() == maxLength) {
return false;
}
if (queue2.isEmpty()) {
queue1.put(item);
} else {
queue2.put(item);
}
return true;
}
/**
* 出栈
* @return
*/
public Object pop() {
if (size() == 0) {
throw new IndexOutOfBoundsException("栈里已经空啦");
} else {
if (queue2.isEmpty()) {
while (queue1.size() > 1) {
queue2.put(queue1.poll());
}
return queue1.poll();
} else {
while (queue2.size() > 1) {
queue1.put(queue2.poll());
}
return queue2.poll();
}
}
}
public int size() {
return queue1.size() + queue2.size();
}
}
相关文章推荐
- JavaShowAlgorithm-使用2个栈实现队列
- java中使用阻塞队列实现生产这与消费这之间的关系
- java使用数组实现优先级队列
- java中使用FIFO队列:java.util.Queue实现多台服务器发邮件的代码
- 使用2个队列实现一个栈
- 使用java.util.concurrent实现的线程池、消息队列功能
- 使用数组实现栈和循环队列(JAVA语言)
- 数据结构——使用双端链表实现队列(java实现)
- JAVA实现最简单的双向链表、队列与栈(内部使用链表形式存储)
- 使用Java程序来实现HTTP文件的队列下载
- java使用两个栈模拟队列的实现
- 使用Java程序来实现HTTP文件的队列下载
- JAVA可阻塞队列-ArrayBlockingQueue子类BlockingQueue的应用,使用它来实现子线程打印10次,主线程打印100次,如此反复
- Java基础课程学习总结,使用LinkedList简单模拟队列数据结构和堆栈数据结构的实现
- 一个方法最多2个线程同时使用的JAVA实现
- java使用数组实现队列
- java redis使用之利用jedis实现redis消息队列
- java 大量数据提交时,使用队列定时提交思路的程序实现
- Java使用阻塞队列BlockingQueue实现线程同步
- java使用数组和链表实现队列示例