【每日一道算法题】用两个栈来实现一个队列

87 阅读1分钟

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

题解:
这道题只需要知道队列的特性是FIFO也就是先进先出,而栈的特性是FILO,也就是先进后出。
对于push操作,题目并没有要求,所以用一个空栈入栈就好。之后的入栈也全是这个栈来维护。
对于pop操作,我们相当于要改变栈的顺序,这时候可以用另一个空栈将入栈的栈倒序一下,然后pop操作即可。
综上所诉,栈1负责入,栈2负责出,出栈时候先保证栈1中没有node。

解题代码如下:

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();
        }else{
            return stack2.pop();
        }
    }
}