使用两个栈实现队列

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

思路:用两个栈来模拟队列,一个栈作为存储,另一个栈作为交换空间。队列的push操作就直接push到第一个栈中,队列的pop操作,需要取得第一个栈低的元素,所以先把第一个栈的元素出栈,入栈到第二个队列,那么取的元素就是第二个栈的栈顶,第二个栈直接出栈即可。然后把剩下的数据在还原回去。

实现代码:

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.isEmpty()) {
            stack2.push(stack1.pop());
        }
        
        int ret = stack2.pop();
        
        while(!stack2.isEmpty()) {
            stack1.push(stack2.pop());
        }
        
        return ret;
    }
}
原文地址:https://www.cnblogs.com/wxisme/p/5236200.html