代码随想录二刷day10

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录

  • 前言
  • 一、力扣232. 用栈实现队列
  • 二、力扣225. 用队列实现栈


前言


一、力扣232. 用栈实现队列

class MyQueue {
    Deque<Integer> deq1;
    Deque<Integer> deq2;

    public MyQueue() {
        this.deq1 = new ArrayDeque<>();
        this.deq2 = new ArrayDeque<>();
    }
    
    public void push(int x) {
        deq1.offerLast(x);
    }
    
    public int pop() {
        while(!deq1.isEmpty()){
            deq2.offerLast(deq1.pollLast());
        }
        int res = deq2.pollLast();
        while(!deq2.isEmpty()){
            deq1.offerLast(deq2.pollLast());
        }
        return res;
    }
    
    public int peek() {
        while(!deq1.isEmpty()){
            deq2.offerLast(deq1.pollLast());
        }
        int res = deq2.peekLast();
        while(!deq2.isEmpty()){
            deq1.offerLast(deq2.pollLast());
        }
        return res;
    }
    
    public boolean empty() {
        return deq1.isEmpty();
    }
}

/**
 * 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. 用队列实现栈

class MyStack {
    Deque<Integer> deq1;
    Deque<Integer> deq2;

    public MyStack() {
        this.deq1 = new ArrayDeque<>();
        this.deq2 = new ArrayDeque<>();
    }
    
    public void push(int x) {
        deq1.offerLast(x);
    }
    
    public int pop() {
        while(deq1.size() > 1){
            deq2.offerLast(deq1.pollFirst());
        }
        int res = deq1.pollFirst();
        while(!deq2.isEmpty()){
            deq1.offerLast(deq2.pollFirst());
        }
        return res;
    }
    
    public int top() {
        while(deq1.size() > 1){
            deq2.offerLast(deq1.pollFirst());
        }
        int res = deq1.peekFirst();
        deq2.offerLast(deq1.pollFirst());
        while(!deq2.isEmpty()){
            deq1.offerLast(deq2.pollFirst());
        }
        return res;
    }
    
    public boolean empty() {
        return deq1.isEmpty();
    }
}

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack obj = new MyStack();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.top();
 * boolean param_4 = obj.empty();
 */

你可能感兴趣的:(java,算法,前端,leetcode,数据结构)