用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
方法一:入栈时,把数据导入stack1;出栈时,将stack1的数据全放到栈stack2,stack2栈顶即为要出栈数据,出栈stack2栈顶数据,然后将stack2的剩余数据全部入栈stack1
import java.util.Stack; public class Solution { Stack<Integer> stack1 = new Stack<Integer>(); Stack<Integer> stack2 = new Stack<Integer>(); public void push(int node) { stack1.push(node); } public int pop() { while(!stack1.isEmpty()){ stack2.push(stack1.pop()); } int temp=stack2.pop(); while(!stack2.isEmpty()){ stack1.push(stack2.pop()); } return temp; } }方法二:这是左程云的《程序员代码面试指南》的答案:,我摘抄过来的。 这个思路很不错
import java.util.Stack; public class Solution { Stack<Integer> stack1 = new Stack<Integer>(); Stack<Integer> stack2 = new Stack<Integer>(); public void push(int node) { stack1.push(node); } public int pop() { if(stack1.isEmpty() && stack2.isEmpty()){ throw new RuntimeException("stack empty"); } if(stack2.isEmpty()){ while(!stack1.isEmpty()){ stack2.push(stack1.pop()); } } return stack2.pop(); } }剑指offer编程题