用两个栈实现队列
用两个栈实现队列
http://www.nowcoder.com/questionTerminal/54275ddae22f475981afa2244dd448c6
import java.util.Stack;
/**
用两个栈实现队列:
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
/
public class offer_5 {
Stack<integer> stack1 = new Stack<integer>();
Stack<integer> stack2 = new Stack<integer>();
public void push(int node) {</integer></integer></integer></integer>stack1.push(node);
}
public int pop() {if (stack2.size()==0&&stack1.size()==0){ return -1; } if (stack2.size() > 0) { return stack2.pop(); } while (stack1.size() > 0) { stack2.push(stack1.peek()); stack1.pop(); } return stack2.pop();
}
public static void main(String[] args) {
offer_5 a = new offer_5(); a.push(1); a.push(2); a.push(5); System.out.println(a.pop()); a.push(4); System.out.println(a.pop()); a.push(3); System.out.println(a.pop()); a.push(7); System.out.println(a.pop()); System.out.println(a.pop()); System.out.println(a.pop());
}
}
应该还有更简单的方法吧