思路:
- 先往 queue1 顺次插入1,2,3,4,5,此时按照栈的规则应先出来 5,所以先将1,2,3,4 出队列 queue1,并入队列 queue2,5 出队列,queue2 当前状态是:1,2,3,4,queue1当前状态为空;
- 将1,2,3入队列 queue1,4 出队列,此时,queue2 为空,queue1 有 1,2,3...
- 重复以上步骤
代码实现:
/**
* 题目类型:队列
*
* 题目要求:用两个队列实现栈
*
* 思路:1. 先往 queue1 顺次插入1,2,3,4,5,此时按照栈的规则应先出来 5,所以先将1,2,3,4 出队列 queue1,并入队列 queue2,5 出队列
* queue2 当前状态是:1,2,3,4,queue1当前状态为空;
* 2. 将1,2,3入队列 queue1,4 出队列,此时,queue2 为空,queue1 有 1,2,3...
* 3. 重复以上步骤
*/
public class QueueToStack {
private Queue<Integer> queue1 = new ArrayDeque<Integer>();
private Queue<Integer> queue2 = new ArrayDeque<Integer>();
/**
* 向栈中压入数据
* @param data
*/
private void push(Integer data) {
if (queue1.isEmpty() && queue2.isEmpty()) {
queue1.add(data);
}
//如果queue1为空,queue2有数据,直接放入queue2
if (queue1.isEmpty()) {
queue2.add(data);
}
if (queue2.isEmpty()) {
queue1.add(data);
}
}
/**
* 从栈中弹出数据
* @return
*/
private Integer pop() throws Exception {
if (queue1.isEmpty() && queue2.isEmpty()) {
throw new Exception("stack is empty");
}
//如果queue1中没有元素,queue2中有元素,将queue2中的元素依次放入queue1中,弹出最后一个元素
if(queue1.isEmpty()){
while(queue2.size() > 1){
queue1.add(queue2.poll());
}
return queue2.poll();
}
//如果queue2中没有元素,queue1中有元素,将其queue1中的元素依次放入queue2中,弹出最后一个元素
if(queue2.isEmpty()){
while(queue1.size() > 1){
// poll() Retrieves and removes the head of this queue 若队列为空,则返回 null
// peek() Retrieves, but does not remove, the head of this queue
queue2.add(queue1.poll());
}
return queue1.poll();
}
return null;
}
@Test
public void testQueue() throws Exception {
QueueToStack queueToStack = new QueueToStack();
queueToStack.push(1);
queueToStack.push(0);
queueToStack.push(6);
queueToStack.push(9);
System.out.println(queueToStack.pop());
System.out.println(queueToStack.pop());
queueToStack.push(2);
System.out.println(queueToStack.pop());
System.out.println(queueToStack.pop());
System.out.println(queueToStack.pop());
}
}