算法训练营第十天|232.用栈实现队列、225. 用队列实现栈

56 阅读1分钟

232. 用栈实现队列

两个栈实现队列,一个in,一个out。

class MyQueue {
    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() {
        //只有当out为空时,才把in中所有数据转移到out
        if(out.empty()){
            while(!in.empty()){
                out.push(in.pop());
            }
        }
        int res = out.pop();
        return res;
    }
    
    public int peek() {
        int res = this.pop();
        out.push(res);
        return res;
    }
    
    public boolean empty() {
        return in.isEmpty() && out.isEmpty();
    }
}

225. 用队列实现栈

感觉就是API的调用

class MyStack {
    Queue<Integer> q;
    public MyStack() {
        q = new LinkedList<Integer>();
    }
    
    public void push(int x) {
        q.offer(x);
        int size = q.size();
        while(size-- > 1){
            q.offer(q.poll());
        }
    }
    
    public int pop() {
        return q.poll();
    }
    
    public int top() {
        return q.peek();
    }
    
    public boolean empty() {
        return q.isEmpty();
    }
}