package NiuKe;
import java.util.Queue;
import java.util.Stack;
//用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
public class Test1 {
static Stack<Integer> stack1 = new Stack<Integer>();
static Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
//入栈操作:全部放入stack1栈中
stack1.push(node);
}
//出栈操作:将所有stack1栈的中的元素全部出栈后入栈至stack2,然后从stack2中模拟队列的出栈操作
public int pop() {
if(stack2.isEmpty()) {
while(!stack1.isEmpty()) {
//将stack1中出栈后的结果入栈到stack2中
stack2.push(stack1.pop());
System.out.println("stack2入栈");
System.out.println(stack2);
}
return stack2.pop();
}
else {
return stack2.pop();
}
}
public static void main(String[] args) {
Test1 a=new Test1();
int b[]= {3,5,3,14,5,65,8,4};
for(int i=0;i<b.length;i++) {
System.out.println("stack1入栈操作");
System.out.println(stack1);
a.push(b[i]);
}
//出栈
for(int j=0;j<b.length;j++) {
System.out.println("stack2出栈");
a.pop();
System.out.println(stack2);
}
}
}
计算结果: