面试题7:栈和队列的互相实现(Leetcode-232和225)

本文介绍如何通过两个栈实现队列的功能,包括push、pop、peek和empty等核心操作;同时探讨了如何利用两个队列来模拟栈的行为,实现了push、pop、top和empty等关键函数。

一. 用两个栈实现队列,实现四个函数:push,pop,peek,empty

思路:
用两个栈实现队列;
一个栈s1用于入队,直接把新元素进s1,就完成了push函数。
另一个栈s2用于出队。如果s2已空,则把s1中的所有元素出栈,并push进s2,最后s2出栈,即完成队列的pop函数。
peek函数是取出队列的对首元素。

代码如下:

class MyQueue {
private:
    stack<int> s1;
    stack<int> s2;
public:
    /** Initialize your data structure here. */
    MyQueue() {  
    }

    /** Push element x to the back of queue. */
    void push(int x) 
    {
        s2.push(x);
    }

    /** Removes the element from in front of queue and returns that element. */
    int pop() 
    {
        if(s1.empty())
        {
            while(!s2.empty())
            {
                int t = s2.top();
                s2.pop();
                s1.push(t);
            }
        }

        int ret = s1.top();
        s1.pop();
        return ret;
    }

    /** Get the front element. */
    int peek() 
    {
        if(s1.empty())
        {
            while(!s2.empty())
            {
                int t = s2.top();
                s2.pop();
                s1.push(t);
            }
        }

        int ret = s1.top();
        return ret;
    }

    /** Returns whether the queue is empty. */
    bool empty() 
    {
        return s1.empty() && s2.empty();
    }
};

二. 用两个队列实现栈,实现四个函数:push,pop,top,empty

思路:
用两个队列q1,q2实现一个栈。push时把新元素添加到q1的队尾。
pop时把q1中除最后一个元素外逐个添加到q2中,然后pop掉q1中的最后一个元素;
这样q1的元素就为空,然后把q2的元素拷贝到q1中,也就是q1和q2交换,
保证下次操作时还是使用q1。
top的道理类似。

注意:push时始终是向q1对尾添加元素,top和pop也是对q1操作,只是q1元素全部出队后,需要把q1和q2交换。
不管top,还是pop,都需要把q1的所有元素出队,做交换前,保证q1队列为空

算法复杂度push是O(1),pop和top都需要交换队列,复杂度是O(n)。

代码如下:

class MyStack {
private:
    queue<int> q1;
    queue<int> q2;

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

    /** Push element x onto stack. */
    void push(int x) {
        q1.push(x);
    }

    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        while(q1.size() > 1)
        {
            q2.push(q1.front());
            q1.pop();
        }

        int a = q1.front();
        q1.pop();

        queue<int> tmp = q1;
        q1 = q2;
        q2 = tmp;

        return a;

    }

    /** Get the top element. */
    int top() {
        while(q1.size() > 1)
        {
            q2.push(q1.front());
            q1.pop();
        }

        int a = q1.front();
        q2.push(a);
        q1.pop();

        queue<int> tmp = q1;
        q1 = q2;
        q2 = tmp;

        return a;

    }

    /** Returns whether the stack is empty. */
    bool empty() {
        return q1.empty();
    }
};
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值