《剑指offer》5.用两个栈实现队列

题目地址:https://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6?tpId=13&tqId=11158&rp=4&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

解题思路:思路很清楚,第一个栈进行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() {
        if(stack2.isEmpty()){
            while(!stack1.isEmpty()){
                stack2.push(stack1.pop());
            }
        }
        if(stack2.isEmpty())
            throw new RuntimeException("queue is Empty");
        return stack2.pop();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_28900249/article/details/89277466