剑指offer9 用两个栈实现队列
用两个栈实现队列
http://www.nowcoder.com/questionTerminal/54275ddae22f475981afa2244dd448c6
方法1:始终在2栈取,如果空就把1栈的数据倒过去
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.add(node); } public int pop() { if(stack2.isEmpty()){ while(!stack1.isEmpty()){ stack2.add(stack1.pop()); } } return stack2.pop(); } }
方法2:始终在1栈操作,每次取数据把栈的n-1个数据倒入2栈,然后操作完再倒回来
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.add(node); } public int pop() { while(stack1.size()>1){ stack2.add(stack1.pop()); } int res=(int)stack1.pop(); while(!stack2.isEmpty()){ stack1.add(stack2.pop()); } return res; } }