剑指offer5:用两个栈实现队列

题目描述:

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

思路:

基本操作,栈是后进先出,队列是先进先出,两个栈正好反反得正

 1 import java.util.Stack;
 2 public class Lianggezhanduilie {
 3     Stack<Integer> stack1 = new Stack<Integer>();
 4     Stack<Integer> stack2 = new Stack<Integer>();
 5        
 6     public void push(int node) {
 7        stack1.push(node);
 8     }
 9        
10     public int pop() {
11         while(stack2.isEmpty()){
12             while(!stack1.isEmpty()){
13                 stack2.push(stack1.pop());    
14             }
15         }
16         int ans = stack2.pop();
17     return ans;
18        
19     }
20     public static void main(String[] args) {
21         // TODO Auto-generated method stub
22 
23     }
24 
25 }
原文地址:https://www.cnblogs.com/zlz099/p/8534675.html