前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >算法(七) 模拟

算法(七) 模拟

作者头像
宇宙无敌暴龙战士之心悦大王
发布2022-01-10 11:25:05
3820
发布2022-01-10 11:25:05
举报
文章被收录于专栏:kwai

模拟

通过其他类来模拟某类的方法,大概就是模拟了吧。

例题

1,栈实现队列

来自LeetCode232

  • 双栈,一个输入栈,一个输出栈,输出栈为空时,输入栈全部进入输出栈。
  • 简单,稍微思考过程即可得出答案。
解法
代码语言:javascript
复制
class MyQueue {
    Stack<Integer> in;
    Stack<Integer> out;
    /** Initialize your data structure here. */
    public MyQueue() {
        in = new Stack<>();
        out = new Stack<>();
    }
  
    /** Push element x to the back of queue. */
    public void push(int x) {
        in.push(x);
    }
  
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        if(out.empty()){
            while(!in.empty()){
                out.push(in.pop());
            }
        }
        return out.pop();
    }
  
    /** Get the front element. */
    public int peek() {
        if(out.empty()){
            while(!in.empty()){
                out.push(in.pop());
            }
        }
        return out.peek();
    }
  
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return in.empty() && out.empty();
    }
}

/**
 * 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();
 */
理解
  • 其实本题有一个很重要的边界问题,就是输入栈输出栈同时为空的情况,但是题目给出不可能了233。
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021-08-20,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 模拟
  • 例题
    • 1,栈实现队列
      • 解法
      • 理解
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档