算法|232. 用栈实现队列、 用队列实现栈

2022-11-24  本文已影响0人  激扬飞雪

一、232. 用栈实现队列

题目链接:https://leetcode.cn/problems/implement-queue-using-stacks/
思路:使用两个栈,一个输入栈input,一个输出栈output,
          push:往input.push()元素
          peek:在output.peek()元素,在执行前检查outpush是否为空 ,为空则input pop出push output中
        pop:在output.pop()元素,在执行前检查outpush是否为空 ,为空则input pop出push output中
        empty:判断input.isEmpty() && outpush.isEmpty();

class MyQueue {
    private Stack<Integer> input;
    private Stack<Integer> output;
    public MyQueue() {
        input = new Stack<>();
        output = new Stack<>();
    }
    
    public void push(int x) {
        input.push(x);
    }

    private void check() {
        if (output.isEmpty()) {
            while (!input.isEmpty()) {
                output.push(input.pop());
            }
        }
    }
    
    public int pop() {
        check();
        return output.pop();
    }
    
    public int peek() {
        check();
        return output.peek();
    }
    
    
    public boolean empty() {
        return input.isEmpty() && output.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. 用队列实现栈

题目链接:https://leetcode.cn/problems/implement-stack-using-queues/
思路:使用一个队列实现,
push:记录size 往队列中添加元素, 将size个元素offer到队列中去
pop:队列poll();
top:队列peek();
empty:判断队列是否为空isEmpty();

class MyStack {
    private Queue<Integer> queue;
    public MyStack() {
        queue = new LinkedList<>();
    }
    
    public void push(int x) {
        int size = queue.size();
        queue.offer(x);
        while (size-- > 0) {
            queue.offer(queue.poll());
        }
    }
    
    public int pop() {
        return queue.poll();
    }
    
    public int top() {
        return queue.peek();
    }
    
    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();
 */
上一篇 下一篇

猜你喜欢

热点阅读