[代码随想录] 第九天

232.栈实现队列[https://leetcode.cn/problems/implement-queue-using-stacks/description/]
思路:无

class MyQueue {
    Stack<Integer> stackIn;
    Stack<Integer> stackOut;
    int temp;

    public MyQueue() {
        stackIn = new Stack<>();
        stackOut = new Stack<>();
    }

    public void push(int x) {
        stackIn.push(x);
    }

    public int pop() {
        while (!stackIn.empty()) {
            temp = stackIn.pop();
            stackOut.push(temp);
        }
        int ans = stackOut.pop();
        while (!stackOut.empty()) {
            temp = stackOut.pop();
            stackIn.push(temp);
        }
        return ans;
    }

    public int peek() {
        while (!stackIn.empty()) {
            temp = stackIn.pop();
            stackOut.push(temp);
        }
        int ans = stackOut.peek();
        while (!stackOut.empty()) {
            temp = stackOut.pop();
            stackIn.push(temp);
        }
        return ans;
    }

    public boolean empty() {
        return stackIn.empty();
    }
}

/**
 * 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.用队列实现栈[https://leetcode.cn/problems/implement-stack-using-queues/submissions/496722251/]
思路:优化只使用了一条队列。

class MyStack {
    Queue<Integer> queue;
    int temp;

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

    public void push(int x) {
        queue.offer(x);
    }

    public int pop() {
        int i = 1;
        while (i < queue.size()) {
            temp = queue.poll();
            queue.offer(temp);
            i++;
        }
        return queue.poll();
    }

    public int top() {
        int i = 1;
        while (i <= queue.size()) {
            temp = queue.poll();
            queue.offer(temp);
            i++;
        }
        return temp;
    }

    public boolean empty() {
        return queue.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();
 */
posted @ 2024-01-19 17:30  糟糕的家伙  阅读(6)  评论(0)    收藏  举报