用两个栈实现一个队列
import java.util.Stack;
public class StackToQueue {
static Stack<Integer> stack1 = new Stack<Integer>();
static Stack<Integer> stack2 = new Stack<Integer>();
public static void push(int node){
stack1.push(node);
}
public static int pop(){
if (stack2.isEmpty()){
while (!stack1.empty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}
用两个队列实现一个栈
import java.util.LinkedList;
import java.util.Queue;
public class QueueToStack {
static Queue<Integer> queue1 = new LinkedList<>();
static Queue<Integer> queue2 = new LinkedList<>();
public static void main(String[] args) {
push(1);
push(2);
push(3);
pop();
push(4);
pop();
pop();
}
public static void pop(){
if (queue1.size() != 0){
while(true) {
if (queue1.size() == 1) {
System.out.println("POP"+queue1.remove());
break;
}
queue2.add(queue1.remove());
}
}else if(queue2.size() != 0){
while(true) {
if (queue2.size() == 1) {
System.out.println("POP"+queue2.remove());
break;
}
queue1.add(queue2.remove());
}
}
}
public static void push(int n){
queue1.add(n);
System.out.println("PUSH"+n);
}
}