队列实现栈结构:使用两个队列,入栈时进入队列1,出栈时将队列1的前n-1个元素压入队列2中,弹出最后一个元素,然后交换队列1与队列2的角色.
import java.util.LinkedList;
import java.util.Queue;
public class TwoQueueStack {
private Queue<Integer> data;
private Queue<Integer> help;
public TwoQueueStack() {
data = new LinkedList<Integer>();
help = new LinkedList<Integer>();
}
public void push(int pushInt) {
data.add(pushInt);
}
public int peek() {
if(data.isEmpty()) {
throw new RuntimeException("Stack is empty!");
}
while(data.size() != 1) {
help.add(data.poll());
}
int res = data.poll();
help.add(res);
swap();
return res;
}
public int pop() {
if(data.isEmpty()) {
throw new RuntimeException("Stack is empty!");
}
while(data.size() > 1) {
help.add(data.poll());
}
int res = data.poll();
swap();
return res;
}
private void swap() {
Queue<Integer> tmp = help;
help = data;
data = tmp;
}
public static void main(String[] args) {
TwoQueueStack stack = new TwoQueueStack();
stack.push(6);
stack.push(8);
System.out.println(stack.pop());
System.out.println(stack.peek());
}
}
运行结果:
栈实现队列结构:进队时将元素压入栈1,然后将栈1元素全部压入栈2(但只有在栈2为空时才执行),出队时取栈2栈顶元素即可.
import java.util.Stack;
public class TwoStackQueue {
private Stack<Integer> stackPush;
private Stack<Integer> stackPop;
public TwoStackQueue() {
stackPush = new Stack<Integer>();
stackPop = new Stack<Integer>();
}
public void push(int pushInt) {
stackPush.push(pushInt);
}
public int poll() {
if(stackPush.isEmpty() && stackPop.isEmpty()) {
throw new RuntimeException("Queue is empty!");
}
pour();
return stackPop.pop();
}
public int peek() {
if(stackPop.isEmpty() && stackPush.isEmpty()) {
throw new RuntimeException("Queue is empty!");
}
pour();
return stackPop.peek();
}
public void pour() {
if(!stackPop.isEmpty()) {
return;
}
while(!stackPush.isEmpty()) {
stackPop.push(stackPush.pop());
}
}
public static void main(String[] args) {
TwoStackQueue queue = new TwoStackQueue();
queue.push(7);
queue.push(4);
System.out.println(queue.peek());
System.out.println(queue.poll());
System.out.println(queue.peek());
queue.push(6);
System.out.println(queue.peek());
}
}
运行结果: