Search code examples
c++queuestack

How can i transfer elements from queue to stack?


A queue Q containing n items and an empty stack s are given. It is required to transfer all the items from the queue to the stack so that the item at the front of queue is on the TOP of the stack, and the order of all other items are preserved.

I tried coding it but it only prints the elements of queue.

#include <iostream>
#include <queue>
#include <stack>

using namespace std;

void Stack(queue<int>& q)
{
    queue<int> s;

    while(!q.empty())
    {
        q.push(s.top());
        q.pop();
    }

    while(!s.empty())
    {
        s.push(q.front());
        s.pop();
    }

    while(!q.empty())
    {
        q.push(s.top());
        q.pop();
    }
}

void printStack(queue<int> a)
{

    while(!a.empty())
    {
       cout<<a.front()<<" ";
       a.pop();
    }
}

int main()
{
    queue<int> q;
    q.push(1);
    q.push(2);
    q.push(3);
    q.push(4);

    cout<<"Queue: ";
    printStack(q);

    cout<<"Stack: ";


return 0;
}

Solution

  • Your transfer function (Stack) is wrong. The exercise it to use the queue and the stack to:

    • Empty the queue by pushing each element on to the stack.
    • Empty the stack by popping each element and pushing it into the queue
    • Empty the queue by pushing each element on to the stack.

    The result will produce a stack whose top is the same as the original queue's front.

    It should look like this:

    #include <iostream>
    #include <queue>
    #include <stack>
    using namespace std;
    
    stack<int> Stack(queue<int>& q)
    {
        stack<int> s;  // notice : stack, not queue
    
        while (!q.empty())
        {
            s.push(q.front());
            q.pop();
        }
    
        while (!s.empty())
        {
            q.push(s.top());
            s.pop();
        }
    
        while (!q.empty())
        {
            s.push(q.front());
            q.pop();
        }
    
        return s;
    }
    
    int main()
    {    
        queue<int> q;
        for (int i=1; i<=10; ++i)
            q.push(i);
    
        // transer the queue to a stack
        stack<int> s = Stack(q);
    
        // print (and empty) the stack.
        while (!s.empty())
        {
            std::cout << s.top() << ' ';
            s.pop();
        }
        std::cout.put('\n');
    }
    

    Output

    1 2 3 4 5 6 7 8 9 10