美文网首页
代码随想录算法训练营第10天|栈与队列part01

代码随想录算法训练营第10天|栈与队列part01

作者: pangzhaojie | 来源:发表于2023-05-23 09:01 被阅读0次

栈实现队列

题目链接

https://programmercarl.com/0232.%E7%94%A8%E6%A0%88%E5%AE%9E%E7%8E%B0%E9%98%9F%E5%88%97.html

思路

两个栈,一个入栈,一个出栈

    class MyQueue {

Stack<Integer> stackIn;
Stack<Integer> stackOut;

public MyQueue() {
    stackIn = new Stack();
    stackOut = new Stack();
}

public void push(int x) {
    stackIn.push(x);
}

public int pop() {
    xx();
    return stackOut.pop();
}

public int peek() {
    xx();
    return stackOut.peek();
}

public boolean empty() {
    return stackIn.isEmpty() && stackOut.isEmpty();
}

private void xx() {
    if(stackOut.isEmpty()) {
        while(!stackIn.isEmpty()) {
            stackOut.push(stackIn.pop());
        }
    }
}
}

队列实现栈

题目链接

https://programmercarl.com/0225.%E7%94%A8%E9%98%9F%E5%88%97%E5%AE%9E%E7%8E%B0%E6%A0%88.html

思路

    class MyStack {

private Queue<Integer> queue;

public MyStack() {
    queue = new LinkedList();
}

public void push(int x) {
    queue.add(x);
}

public int pop() {
    xx();
    return queue.poll();
}

public int top() {
    xx();
    int a = queue.poll();
    queue.add(a);
    return a;
}

private void xx() {
    int size = queue.size();
    size--;
    while(size > 0){
        queue.add(queue.poll());
        size--;
    }
}

public boolean empty() {
    return queue.isEmpty();
}
}

相关文章

  • 算法-栈和队列算法总结

    栈和队列算法总结 1 模拟 1.1 使用栈实现队列 1.2 使用队列实现栈 2 栈的应用 2.1 栈操作 2.2 ...

  • 数据结构——栈和队列

    用数组实现栈和队列 用栈实现队列 用队列实现栈 栈和队列的经典算法题最小间距栈宠物收养所 数组实现栈和队列 用数组...

  • 数据结构的各种代码

    第 02 章 线性表 顺序存储结构 链式存储结构 第 03 章 栈与队列 顺序栈 链栈 两栈共享空间 循环队列 链...

  • 排序算法

    什么是算法 书籍推荐 《数据结构与算法分析》 表、栈和队列 树 散列(hash) 优先队列(堆) 排序 定义 问题...

  • P61-用两个队列实现一个栈

    法1:《剑指》的思路 代码: C++算法之 两个队列实现一个栈 法2:更加简单 思路: 在实现时使得栈顶等于队列头...

  • 队列之-队列实现栈

    一、队列实现栈核心算法概述 之前已经描述过了用栈实现队列的功能,见栈系列之-实现队列,那么同样队列也可以用来实现栈...

  • 集合相关数据结构与算法

    队列 栈数据结构 比较算法 Collections Collection与Collections的区别?Colle...

  • 数据结构与算法目录

    操作系统目录 哈希树遍历链表数组排序堆与栈队列高级算法

  • Swift 队列&栈 相关操作

    栈 LIFO(后进先出) 队列 FIFO(先进先出) 队列与栈相互的实现 栈 - 队列实现 队列 - 栈实现 相关...

  • 数据结构和算法-4.1-栈

    栈&队列 与 数组的区别 用途:数组,链表,树等一般用来作为数据存储的工具,栈和队列更多是用来作为构思程序算法的辅...

网友评论

      本文标题:代码随想录算法训练营第10天|栈与队列part01

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