剑指offer——用两个栈实现队列

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

解题思路:

当stack2不为空时,在stack2中的栈顶元素是最先进入队列的元素,可以弹出。当stack2为空时,我们把stack1中的元素逐个弹出并压入stack2.由于先进入队列的元素被压到stack1,底端,经过弹出和压入操作后就处于stack2的顶端。

 1 import java.util.Stack;
 2 
 3 public class Solution {
 4     Stack<Integer> stack1 = new Stack<Integer>();
 5     Stack<Integer> stack2 = new Stack<Integer>();
 6     
 7     public void push(int node) {
 8         stack1.push(node);
 9     }
10     
11     public int pop() {
12         if(stack2.empty())//如果stack2不为空,不可以push
13         {
14             while(!stack1.empty())
15             stack2.push(stack1.pop());
16             
17         }
18         return stack2.pop();
19     
20     }
21 }
原文地址:https://www.cnblogs.com/wangyufeiaichiyu/p/10844442.html