代码随想录算法训练营第九天 | 栈与队列

225. 用栈实现队列

需要注意:实现peek时不能调用pop()方法,否则会打乱原队列顺序

class MyQueue {
    
    Stack<Integer> stack;
    Stack<Integer> tmp;

    public MyQueue() {
        stack = new Stack<>();
        tmp = new Stack<>();
    }
    
    public void push(int x) {
        stack.push(x);
    }
    
    public int pop() {
        if (stack.size() == 1) return stack.pop();
        while(stack.size() > 1) tmp.push(stack.pop());
        int popped = stack.pop();
        while(!tmp.isEmpty()) stack.push(tmp.pop());
        return popped;
    }
    
    public int peek() {
        if (stack.size() == 1) return stack.peek();
        while(stack.size() > 1) tmp.push(stack.pop());
        int topElement = stack.peek();
        while(!tmp.isEmpty()) stack.push(tmp.pop());
        return topElement;
    }
    
    public boolean empty() {
        return stack.isEmpty();
    }
}

225. 用队列实现栈

可使用一个队列实现

class MyStack {
    
    Queue<Integer> queue;

    public MyStack() {
        queue = new LinkedList<>();
    }
    
    public void push(int x) {
        queue.offer(x);
    }
    
    public int pop() {
        if (queue.size() == 1) return queue.poll();
        int n = queue.size() - 1;
        for (int i = 0; i < n; i++){
            queue.offer(queue.poll());
        }
        return queue.poll();
    }
    
    public int top() {
        int topElement = pop();
        queue.offer(topElement);
        return topElement;
    }
    
    public boolean empty() {
        return queue.isEmpty();
    }
}

待研究:

为什么LeetCode中:

Stack的实现方法是Stack<T> stack = new Stack<>()

Queue的实现方法是Queue<T> queue = new LinkedList<>()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值