05用两个栈实现队列

题目描述

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

思路分析

两个栈,队列进=数据栈进,队列出=当后备栈为空时,将数据栈所有元素弹出+后备栈进,后备栈出。

代码实现

Stack<Integer> stackData = new Stack<>();
Stack<Integer> stackBack = new Stack<>();

public void push(int node) {
    stackData.push(node);
}

public int pop() {
    if (stackBack.isEmpty()) {
        while (!stackData.isEmpty()) {
            stackBack.push(stackData.pop());
        }
    }
    return stackBack.pop();
    /*等价
	if (!stackBack.isEmpty()) {
        return stackBack.pop();
    }
    while (!stackData.isEmpty()) {
        stackBack.push(stackData.pop());
    }
    return stackBack.pop();
    */
}
发布了71 篇原创文章 · 获赞 3 · 访问量 2419

猜你喜欢

转载自blog.csdn.net/qq_34761012/article/details/104310619