剑指offer(5)

题目:

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

解法:

  一个栈专门用来存数,当需要输出数时,把所有数倒到第二个栈,当然,若此时第二个栈中已经有数了(之前倒过来的),那么就可以直接输出,推荐画一下图,这样就可以实现先进先出的队列了。

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(stack1.isEmpty()&&stack2.isEmpty()){
            throw new RuntimeException("Queue is empty!");
        }
        if(stack2.isEmpty()){
            while(!stack1.isEmpty()){
                stack2.push(stack1.pop());
            }
        }
        return stack2.pop();
    }
}

  

原文地址:https://www.cnblogs.com/figsprite/p/10451109.html