剑指offer——两个栈实现队列与两个队列实现栈

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/puliao4167/article/details/85172211

题目描述:两个栈实现队列

解题思路:栈是“先进后出”,队列是“先进先出”。操作“入队列”:利用两个栈s1和s2,元素进的时候,放入s1即可。操作“出队列”:先检查s2是否为空,如果不为空,直接pop出s2的元素,如果为空,则把s1的元素都pop出来,然后依次放入s2中,再对s2进行pop即可。

class Solution
{
public:
    void push(int node) {
        stack1.push(node);
    }

    int pop() {
        if(stack2.empty())
        {
            while(!stack1.empty())
            {
                int n=stack1.top();
                stack1.pop();
                stack2.push(n);
            }
        }
        int n=stack2.top();
        stack2.pop();
        return n;
    }

private:
    stack<int> stack1;
    stack<int> stack2;
};

题目描述:两个队列实现一个栈

解题思路:对于两个队列,把一个作为输入输出队列,另一个作为中转队列。两个队列q1和q2,输入都放在q1,输出时,除了q1中最后一个元素,其他都放到q2中,当输出q1中最后一个元素后,再把q2中的元素都放回q1。

#include <iostream>
#include <vector>
#include <stack>
#include <queue>
using namespace std;

class STACK
{
public:
    void push(int node)
    {
        q1.push(node);
    }
    int pop()
    {
        int sz=q1.size();
        int n;
        for(int i=0;i<sz-1;i++)
        {
            n=q1.front();
            q1.pop();
            q2.push(n);
        }
        n=q1.front();
        q1.pop();

        while(!q2.empty())
        {
            q1.push(q2.front());
            q2.pop();
        }
        return n;

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

};


int main()
{
    STACK s;
    s.push(1);
    s.push(2);
    s.push(3);
    cout<<s.pop()<<endl;
    cout<<s.pop()<<endl;
    s.push(4);
    cout<<s.pop()<<endl;
    cout<<s.pop()<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/puliao4167/article/details/85172211