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

58 阅读1分钟

今日任务:

●  理论基础

●  232.用栈实现队列

●  225. 用队列实现栈

232. 用栈实现队列

双栈实现栈的翻转,从而实现队列的先入先出

class MyQueue {
    //双栈实现
    //一个进栈,一个出栈
    Deque<Integer> inStack;
    Deque<Integer> outStack;

    public MyQueue() {
        inStack = new ArrayDeque<>();
        outStack = new ArrayDeque<>();
    }
    
    public void push(int x) {
        inStack.push(x);
    }
    
    public int pop() {
        if(outStack.isEmpty()) {
            int2out();
        }
        return outStack.pop();
    }
    
    public int peek() {
        if(outStack.isEmpty()) {
            int2out();
        }
        return outStack.peek();
    }
    
    public boolean empty() {
        return inStack.isEmpty() && outStack.isEmpty();
    }
    private void int2out() {
        while(!inStack.isEmpty()) {
            outStack.push(inStack.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();
 */

225. 用队列实现栈

在push的时候进行元素的反转

class MyStack {
    LinkedList<Integer> list;
    public MyStack() {
        list = new LinkedList<>();
    }

    public void push(int x){
        list.addLast(x);
        for(int i = 0; i < list.size() - 1; i++) {
            list.addLast(list.removeFirst());
        }
    }

    public int pop() {
        return list.removeFirst();
    }

    public int top() {
        return list.peekFirst();
    }

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