如何用栈结构实现队列结构
栈:先进后出
队列:先进先出
那么我们需要2个栈 POP和 PUSH
开始左右数据都在push 如果需要出栈时候 把POP里面的都弹出 push到PUSH栈中 那么PUSH栈再弹出就是根据队列的顺序。
但是再add POP队列时候,需要看下PUSH栈有无数据,有数据就不能整体往里面迁入,需要等PUSH都出去 再整体往里面push 这样就转化成了队列
public static class TwoStacksQueue {
public Stack<Integer> stackPush;
public Stack<Integer> stackPop;
public TwoStacksQueue() {
stackPush = new Stack<Integer>();
stackPop = new Stack<Integer>();
}
// push栈向pop栈倒入数据
private void pushToPop() {
if (stackPop.empty()) {
while (!stackPush.empty()) {
stackPop.push(stackPush.pop());
}
}
}
public void add(int pushInt) {
stackPush.push(pushInt);
pushToPop();
}
public int poll() {
if (stackPop.empty() && stackPush.empty()) {
throw new RuntimeException("Queue is empty!");
}
pushToPop();
return stackPop.pop();
}
public int peek() {
if (stackPop.empty() && stackPush.empty()) {
throw new RuntimeException("Queue is empty!");
}
pushToPop();
return stackPop.peek();
}
}
如何用队列结构实现栈结构
栈:先进后出
队列:先进先出
我们需要2个队列A和B 数据先都进A 当需要数据时候 A都进入B 最后一个返回
此时再进数据都进B 需要数据时候B都进A 最后一个返回 以此类推
public static class TwoQueueStack<T> {
public Queue<T> queue;
public Queue<T> help;
public TwoQueueStack() {
queue = new LinkedList<>();
help = new LinkedList<>();
}
public void push(T value) {
queue.offer(value);
}
public T poll() {
while (queue.size() > 1) {
help.offer(queue.poll());
}
T ans = queue.poll();
Queue<T> tmp = queue;
queue = help;
help = tmp;
return ans;
}
public T peek() {
while (queue.size() > 1) {
help.offer(queue.poll());
}
T ans = queue.poll();
help.offer(ans);
Queue<T> tmp = queue;
queue = help;
help = tmp;
return ans;
}
public boolean isEmpty() {
return queue.isEmpty();
}
}