Day10 栈与队列part01

理论基础

了解一下 栈与队列的内部实现机制,文中是以C++为例讲解的。

文章讲解:代码随想录

232.用栈实现队列

大家可以先看视频,了解一下模拟的过程,然后写代码会轻松很多。

题目链接/文章讲解/视频讲解:代码随想录

class MyQueue {
    private Deque stackin ;
    private Deque stackout ;

    public MyQueue() {
        stackin = new ArrayDeque<>();
        stackout = new ArrayDeque<>();
    }
    
    public void push(int x) {
        stackin.push(x);    
    }
    
    public int pop() {
        if(empty()){
            return -1;
        }
        if(stackout.isEmpty()){
            while(!stackin.isEmpty()){
                stackout.push(stackin.pop());
            }
        }
        return stackout.pop();       
    }
    
    public int peek() {
        int num = pop();
        stackout.push(num);
        return num;   
    }
    
    
    public boolean empty() {
        if(stackin.isEmpty() && stackout.isEmpty()){
            return true;
        }
        return 

你可能感兴趣的:(Day10 栈与队列part01)