【经典算法题】用队列实现栈

【经典算法题】用队列实现栈

Leetcode 0225 用队列实现栈

题目描述:Leetcode 0225 用队列实现栈

在这里插入图片描述

分析

  • 本题的考点:设计

  • 使用两个队列q, wq用于存储元素,w是缓存队列。

  • 每次插入元素时,向q中插入元素;

  • 删除栈顶元素时,可以先将队列中前q.size()-1个元素存储到缓存队列w中,最后将q中剩余的一个元素缓存到临时变量t中,然后删除q中最后一个元素,最后将w中的元素再次放入q中即可;

  • 返回栈顶元素的操作和删除类似;

  • 栈是否为空只需要看q是否为空即可。

代码

  • C++
class MyStack {
public:

    queue<int> q, w;

    /** Initialize your data structure here. */
    MyStack() {

    }
    
    /** Push element x onto stack. */
    void push(int x) {
        q.push(x);
    }
    
    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        while (q.size() > 1) w.push(q.front()), q.pop();
        int t = q.front(); q.pop();
        while (w.size()) q.push(w.front()), w.pop();
        return t;
    }
    
    /** Get the top element. */
    int top() {
        while (q.size() > 1) w.push(q.front()), q.pop();
        int t = q.front(); q.pop();
        while (w.size()) q.push(w.front()), w.pop();
        q.push(t);
        return t;
    }
    
    /** Returns whether the stack is empty. */
    bool empty() {
        return q.empty();
    }
};
  • Java
class MyStack {

    Queue<Integer> q = new LinkedList<>(), w = new LinkedList<>();

    /** Initialize your data structure here. */
    public MyStack() {

    }
    
    /** Push element x onto stack. */
    public void push(int x) {
        q.add(x);
    }
    
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        while (q.size() > 1) w.add(q.remove());
        int t = q.remove();
        while(w.size() != 0) q.add(w.remove());
        return t;
    }
    
    /** Get the top element. */
    public int top() {
        while (q.size() > 1) w.add(q.remove());
        int t = q.remove();
        while(w.size() != 0) q.add(w.remove());
        q.add(t);
        return t;
    }
    
    /** Returns whether the stack is empty. */
    public boolean empty() {
        return q.isEmpty();
    }
}

时空复杂度分析

  • 时间复杂度:toppop操作和栈中元素个数成正比,其余操作是 O ( 1 ) O(1) O(1)的。

  • 空间复杂度: O ( n ) O(n) O(n)n为栈中元素个数。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值