码随想录算法训练营第10天 | 232.用栈实现队列 、225. 用队列实现栈

88 阅读1分钟

理论基础 

栈与队列的底层实现

文章讲解:programmercarl.com/%E6%A0%88%E…

 232.用栈实现队列 

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() {
        dumpstackIn();
        return stackOut.pop();
    }
    
    public int peek() {
        dumpstackIn();
        return stackOut.peek();
    }
    
    public boolean empty() {
       return stackIn.isEmpty() && stackOut.isEmpty(); 
    }

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

/**
 * 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();
 */

题目链接/文章讲解/视频讲解:programmercarl.com/0232.%E7%94…

  225. 用队列实现栈 

class MyStack {

    Queue<Integer> queue;

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

    //每 offer 一个数(A)进来,都重新排列,把这个数(A)放到队列的队首
    public void push(int x) {
        queue.offer(x);
        int size = queue.size();
        //移动除了 A 的其它数
        while (size-- > 1)
            queue.offer(queue.poll());
    }

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

    public int top() {
        return queue.peek();
    }

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

题目链接/文章讲解/视频讲解:programmercarl.com/0225.%E7%94…