用两个栈实现队列

解题思路:
入队时,将元素压入s1。
出队时,将s1的元素逐个“倒入”(弹出并压入)s2,将s2的顶元素弹出作为出队元素,之后再将s2剩下的元素逐个“倒回”s1。

用两个栈实现队列_第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() {
        while(!stack1.empty()){
            stack2.push(stack1.pop());
        }
        int val = stack2.pop();
        while(!stack2.empty()){
            stack1.push(stack2.pop());
        }
        return val;

    }
}

你可能感兴趣的:(栈,算法面试题)