模拟

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

例题

1,栈实现队列

来自LeetCode232

  • 双栈,一个输入栈,一个输出栈,输出栈为空时,输入栈全部进入输出栈。
  • 简单,稍微思考过程即可得出答案。

解法

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。