package cn.dzp.flyroc.offer; import java.util.Stack; public class PushAndPopDemo { /*题目描述:用两个栈来实现一个队列,完成队列的Push和pop操做。 队列中的元素为int类型*/ /*思路:一个栈压入元素,而另外一个栈做为缓冲, 将栈1的元素出栈后压入栈2中,也能够将栈一中的最后一个元素直接出栈 而不用再压入栈2中再出栈*/ static Stack<Integer> stack1 = new Stack<>(); static Stack<Integer> stack2 = new Stack<>(); public static void push(int node){ System.out.println("这是第"+node+"个push的元素:"+stack1.push(node)); //将元素压入stack1中 } public static int pop() { if (stack1.isEmpty() && stack2.isEmpty()){ //判断stack1和stack2是否为空 System.out.println("栈为空!"); } if (stack2.isEmpty()){ //判断stack2是否为空 while (!stack1.isEmpty()){ stack2.push(stack1.pop()); //将stack1中弹出的元素压入stack2中,直到stack1为空 } } System.out.println("这是pop第一个元素:"+stack2.pop()); return stack2.pop(); } public static void main(String[] args){ push(1); push(2); push(3); pop(); } }