5.用两个栈实现队列

题目描述:

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

思路分析:

  push操作比较简单,可以用一个栈的push来表示队列的push,pop操作就是将栈1的数据弹出,压入到栈2,那么栈2顶部的元素就是要弹出的元素,但是要注意的是如果要将栈1的数据压入栈2,那么栈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.push(node);
    }
    
    public int pop() {
    if(stack2.isEmpty()){
        while(!stack1.isEmpty()){
            stack2.push(stack1.pop());
        }
        
    }
        return stack2.pop();
    }
}
原文地址:https://www.cnblogs.com/yjxyy/p/10696738.html