算法训练营Day10(栈和队列)

理论知识

java语言的栈和队列。这篇文章总结的不错

http://t.csdnimg.cn/cOC8q

232.用栈实现队列 

232. 用栈实现队列 - 力扣(LeetCode)

public class MyQueue {
    //     3 4
    // in
    // out 4 3
    Stack<Integer> in;
    Stack<Integer> out;

    public MyQueue() {
        in = new Stack<>();
        out = new Stack<>();
    }

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

    public int pop() {
        //先看需不需要补充元素
        dumpOut();
        return out.pop();
    }

    private void dumpOut() {
        //不为空,直接结束方法
        if(!out.isEmpty()) return;
        while(!in.isEmpty()){
            out.push(in.pop());
        }
    }

    public int peek() {
        dumpOut();
        return out.peek();
    }

    public boolean empty() {
        return in.isEmpty()&&out.isEmpty();
    }

}

 225. 用队列实现栈

225. 用队列实现栈 - 力扣(LeetCode)

public class MyStack {
    Queue<Integer> queue;
    public MyStack() {
        queue = new LinkedList<>();
    }

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

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

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

    public int top() {
        rePositon();
        int res = queue.poll();
        queue.offer(res);
        return res;
    }

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

最近更新

  1. TCP协议是安全的吗?

    2023-12-09 07:22:02       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-09 07:22:02       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-09 07:22:02       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-09 07:22:02       20 阅读

热门阅读

  1. LinuxBasicsForHackers笔记 -- 使用和滥用服务

    2023-12-09 07:22:02       33 阅读
  2. 开启数字化转型的关键是什么?

    2023-12-09 07:22:02       26 阅读
  3. velocity-engine-core是什么?Velocity模板引擎的使用

    2023-12-09 07:22:02       36 阅读
  4. Linux C语言 37- 进程间通信IPC

    2023-12-09 07:22:02       40 阅读
  5. 力扣刷题笔记——反转链表

    2023-12-09 07:22:02       43 阅读
  6. 使用rawpy库将raw格式照片转换为其他格式

    2023-12-09 07:22:02       38 阅读
  7. GO设计模式——6、原型模式(创建型)

    2023-12-09 07:22:02       40 阅读
  8. 雷达点云数据.pcd格式转.bin格式

    2023-12-09 07:22:02       46 阅读
  9. harbor仓库镜像迁移脚本

    2023-12-09 07:22:02       24 阅读
  10. C_15练习题

    2023-12-09 07:22:02       33 阅读
  11. ubuntu22.04安装过程记录

    2023-12-09 07:22:02       47 阅读
  12. blender 数字键盘上的快捷键

    2023-12-09 07:22:02       47 阅读