美文网首页数据结构与算法
剑指 Offer 09 用两个栈实现队列

剑指 Offer 09 用两个栈实现队列

作者: itbird01 | 来源:发表于2021-12-04 08:29 被阅读0次

剑指 Offer 09. 用两个栈实现队列

题意:用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )

解题思路

解法:
1.用两个栈,pushStack用于模拟入队操作,每次入队,加入pushStack即可
2.popStack用于模拟出队操作,每次出队,将pushStack中所有元素出栈,入到popStack里面,然后popStack栈底元素即为所求元素
3.别忘记,还原pushStack,即将popStack栈元素一一出栈,入栈到pushStack即可

解题遇到的问题

后续需要总结学习的知识点

##解法1
import java.util.Stack;

class CQueue {
    Stack<Integer> popStack = null;
    Stack<Integer> pushStack = null;
    public CQueue() {
        popStack = new Stack<Integer>();
        pushStack = new Stack<Integer>();
    }

    public void appendTail(int value) {
        pushStack.push(value);
    }

    public int deleteHead() {
        popStack.clear();

        while (!pushStack.isEmpty()) {
            popStack.push(pushStack.pop());
        }

        int ans = -1;
        boolean flag = true;

        while (!popStack.isEmpty()) {
            if (flag) {
                ans = popStack.pop();
                flag = false;
            } else {
                pushStack.push(popStack.pop());
            }
        }
        return ans;
    }
}

/**
 * Your CQueue object will be instantiated and called as such:
 * CQueue obj = new CQueue();
 * obj.appendTail(value);
 * int param_2 = obj.deleteHead();
 */

相关文章

网友评论

    本文标题:剑指 Offer 09 用两个栈实现队列

    本文链接:https://www.haomeiwen.com/subject/klrmxrtx.html