Leetcode-面试题 03.04 化栈为队

作者: itbird01 | 来源:发表于2021-10-12 06:54 被阅读0次

面试题 03.04. 化栈为队

解题思路

用两个栈来实现一个队列
1.队列的特性是先进先出,后进后出
2.题意分析:一个栈用来push操作,一个栈用来pop操作,peek操作也是第二个栈,empty操作就是判断第一个栈是否为空
3.每次pop或者peer时,需要先把pop栈清空,然后将push栈出栈,入栈到pop栈,此时相当于push栈中元素顺序颠倒,此时pop栈进行pop或者peer操作,即为队首元素
4.题意中设定,假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作),所以pop或者peer操作时不需要判断栈是否为空

解题遇到的问题

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

1.用liist或者deque去实现?
2.deque源码如何实现的?

##解法
import java.util.Stack;

class MyQueue {
    Stack<Integer> pushStack = null;
    Stack<Integer> popStack = null;

    /** Initialize your data structure here. */
    public MyQueue() {
        pushStack = new Stack<Integer>();
        popStack = new Stack<Integer>();
    }

    /** Push element x to the back of queue. */
    public void push(int x) {
        pushStack.push(x);
        popStack.clear();
    }

    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        popStack.clear();

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

        int resunt = popStack.pop();
        while (!popStack.isEmpty()) {
            pushStack.push(popStack.pop());
        }
        return resunt;
    }

    /** Get the front element. */
    public int peek() {
        popStack.clear();
        while (!pushStack.isEmpty()) {
            popStack.push(pushStack.pop());
        }
        int resunt = popStack.peek();
        while (!popStack.isEmpty()) {
            pushStack.push(popStack.pop());
        }

        return resunt;
    }

    /** Returns whether the queue is empty. */
    public boolean empty() {
        return pushStack.isEmpty();
    }
}

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue obj = new MyQueue();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.peek();
 * boolean param_4 = obj.empty();
 */

相关文章

  • Leetcode-面试题 03.04 化栈为队

    面试题 03.04. 化栈为队[https://leetcode-cn.com/problems/implemen...

  • 682. 棒球比赛、面试题 03.04. 化栈为队

    今天是栈操作。 682. 棒球比赛[https://leetcode-cn.com/problems/baseba...

  • JavaScript 力扣算法记录-持续更新2

    11.栈的最小值 解题 12.化栈为队 解题 13.节点间通路 解题 14.化栈为队 解题 15.栈排序 解题 1...

  • 化栈为队

    题目: 题目的理解 一开始的时候感觉是实现一个栈,最后才发现实现一个队列,好吧。python的list已经实现了。...

  • 数据结构 栈和队列

    数据结构 栈和队列 栈 顺序栈 top = -1 链栈 初始化 判断队空 入队: 头插法 出队: 单链表删除 队列...

  • LeetCode题解之化栈为队

    化栈为队 题目描述 实现一个MyQueue类,该类用两个栈来实现一个队列。 示例: 说明: 你只能使用标准的栈操作...

  • 手撕栈队列

    【面试题07:用两个栈实现队列】 题目:利用两个栈实现队列的插入,取队首,判断非空等函数。拓展:用两个队列实现栈,...

  • Leetcode-面试题 03.05 栈排序

    面试题 03.05. 栈排序[https://leetcode-cn.com/problems/sort-of-s...

  • 使用栈实现队列

    思路: 思路比较简单,使用两个栈,一个栈A负责入队,一个栈B负责出队,出队的时候,先判断栈B的元素是否为空,如果为...

  • 用两个栈实现队列

    入队:将元素进栈A 出队:判断栈B是否为空,如果为空,则将栈A中所有元素pop,并push进栈B,栈B出栈; 如果...

网友评论

    本文标题:Leetcode-面试题 03.04 化栈为队

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