利用队列实现栈(中等)

使用一个队列

class MyStack {
public:
    //单链表实现
    //在栈中元素的顺序应该是和队列中的顺序相反的,因此整体的思路是元素插入后,将插入元素之前的所有元素出队列重新入队列,这样就可以吧顺序调转过来,这样元素的顺序就一致了,栈中的其他操作就和队列中的操作一致了。时间复杂度为O(n)。
    /** Initialize your data structure here. */
    MyStack() {

    }
    /** Push element x onto stack. */
    void push(int x) {
        q.push(x);
        int sz = q.size();
        while(sz>1) //把插入元素之前的所有元素出队列在入队列。
        {
            q.push(q.front());
            q.pop();
            sz--;
        }
    }
    
    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        int tmp = q.front();
        q.pop();
        return tmp;
    }
    
    /** Get the top element. */
    int top() {
        return q.front();
    }
    
    /** Returns whether the stack is empty. */
    bool empty() {
        return q.empty();
    }

    private:
        queue<int> q;
};

使用两个队列

class MyStack2 {
//双队列实现栈
    //主要思路类似于一个队列的实现,有一个空队列负责插入元素,插入后,将另一个队列中的所有元素出队列然后入新队列,这样实现的顺序的反转,然后两个队列互相交换。保证q2是空队列,q1是存放元素队列。时间复杂度O(n)。相比于一个队列的方法,这种方式占用资源较多,因此通常使用一个队列就够了。
public:
    /** Initialize your data structure here. */
    MyStack2() {

    }
    
    /** Push element x onto stack. */
    void push(int x) {
        q2.push(x);
        while(!q1.empty())
        {
            q2.push(q1.front());
            q1.pop();
        }
        queue<int> temp = q1;
        q1=q2;
        q2=temp;
    }
    
    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        int val = q1.front();
        q1.pop();
        return val;
    }
    
    /** Get the top element. */
    int top() {
        return q1.front();
    }
    
    /** Returns whether the stack is empty. */
    bool empty() {
        return q1.empty();
    }

private:
    queue<int> q1;
    queue<int> q2;
};

/**
 * 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();
 * bool param_4 = obj->empty();
 */

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值