05、两个栈实现一个队列,两个队列实现一个栈

题目描述:

1. 用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

2. 用两个队列来实现一个栈,完成栈的Push和Pop操作。 队列中的元素为int类型。

解题思路:

1. 入队时,直接压入stack1中;出队时,判断stack2是否为空,如果stack2为空,则将stack1中的元素倒入stack2中,否则直接弹出stack2中的元素。

2. 将queue1用作进栈出栈,queue2作为一个中转站。入栈时,直接压入queue1中;出栈时,先将queue1中的元素除最后一个元素外依次出队列,并压入队列queue2中,将留在queue1中的最后一个元素出队列即为出栈元素,最后还要把queue2中的元素再次压入queue1中。

Demo:

//入队操作
void push(stack<int> &s1, stack<int> &s2, int m)
{
    s1.push(m);
}

//出队操作
int pop(stack<int> &s1,stack<int> &s2)
{
    if (s2.empty())
    {
        while (!s1.empty())
        {
            s2.push(s1.top());
            s1.pop();
        }    
    }
    int tmp = s2.top();
    s2.pop();
    return tmp;
}
//进栈操作
void push(queue<int> &q1,queue<int> &q2, int m)
{
    q1.push(m);
}

//出栈操作
int pop(queue<int> &q1,queue<int> &q2)
{
    int p = q1.size();
    for (int i = 0; i < p-1; ++i)
    {
        q2.push(q1.front());
        q1.pop();
    }
    int tmp = q1.front();
    q1.pop();
    int l = q2.size();
    for (int j = 0; j < l; ++j)
    {
        q1.push(q2.front());
        q2.pop();
    }
    return tmp;
}

参考:https://www.cnblogs.com/tracyhan/p/5490775.html

猜你喜欢

转载自blog.csdn.net/daaikuaichuan/article/details/83960259
今日推荐