import java.util.LinkedList;
import java.util.Stack;
/**
* 用两个栈实现队列
*/
public class JZ005TwoStacksImpAQueue {
Stack<Integer> stack1 = new Stack<>();
Stack<Integer> stack2 = new Stack<>();
public void push(int node) {
stack1.push(node);
}
public int pop() throws Exception {
if (stack1.isEmpty() && stack2.isEmpty()) {
throw new Exception("two stacks are empty");
}
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
/*
用两个栈实现队列
总结:
1、需要考虑的是在stack2出栈的时候,stack1这时候有进栈
2、栈和队列的区分:
- 栈:先进后出
- 队列:先进先出
3、延伸:用两个队列实现栈 网上找到了一个非常好的Blog:https://blog.csdn.net/cherrydreamsover/article/details/80466781
*/
LinkedList<Integer> queue1 = new LinkedList<>();
LinkedList<Integer> queue2 = new LinkedList<>();
public void sPop(int node) {
queue1.add(node);
}
public int sPush() throws Exception {
if (queue1.isEmpty() && queue2.isEmpty()) {
throw new Exception("queue is null");
}
while (queue1.size() > 1) {
queue2.add(queue1.poll());
}
int result = queue1.poll();
while (!queue2.isEmpty()) {
queue1.add(queue2.poll());
}
return result;
}
}