day10 打卡232. 用栈实现队列 225. 用队列实现栈

day10 打卡232. 用栈实现队列 225. 用队列实现栈

232. 用栈实现队列

232题目链接

class MyQueue {
    // 管理进的元素
    Stack<Integer> stackIn;
    // 管理出的元素
    Stack<Integer> stackOut;

    public MyQueue() {
        this.stackIn = new Stack();
        this.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());
        }
    }
}

225. 用队列实现栈

225题目链接

1.使用两个队列

class MyStack {
    // 跟栈保持一样的元素
    Queue<Integer> queue1;
    // 辅助队列,每次都是空的
    Queue<Integer> queue2;

    public MyStack() {
        this.queue1 = new LinkedList<>();
        this.queue2 = new LinkedList<>();
    }
    
    public void push(int x) {
        queue2.offer(x);
        while (!queue1.isEmpty()) {
            queue2.offer(queue1.poll());
        }
        Queue<Integer> temp = queue1;
        queue1 = queue2;
        queue2 = temp;
    }
    
    public int pop() {
        return queue1.poll();
    }
    
    public int top() {
        return queue1.peek();
    }
    
    public boolean empty() {
        return queue1.isEmpty();
    }
}

2.使用一个队列

class MyStack {
    Queue<Integer> queue;

    public MyStack() {
        this.queue = new LinkedList<>();
    }
    
    public void push(int x) {
        // 每次加进来元素都需要重新排序
        queue.offer(x);
        int size = queue.size();
        while (size-1>0) {
            Integer num = queue.poll();
            queue.offer(num);
            size--;
        }
    }
    
    public int pop() {
        return queue.poll();
    }
    
    public int top() {,
        return queue.peek();
    }
    
    public boolean empty() {
        return queue.isEmpty();
    }
}

参考资料

代码随想录

posted @ 2023-03-10 20:40  zzzzzzsl  阅读(14)  评论(0)    收藏  举报