how to print out all elements in a std::stack or std::queue conveniently

后端 未结 8 1713
忘掉有多难
忘掉有多难 2020-12-14 20:46

If I do not to want to create a new container in order to do so?

8条回答
  •  感情败类
    2020-12-14 21:50

    It can be easily done using recursion you just need to know when to re-add the next element

    For Stack

    void print(stack &s)
    {
        if(s.empty())
        {
            cout << endl;
            return;
        }
        char x= s.top();
        s.pop();
        print(s);
        s.push(x);
        cout << x << " ";
     }
    

    And this one is For Queue

    void print(queue &s,int num)
    {
        if(!num)
        {
            cout << endl;
            return;
        }
        char x= s.front();
        s.pop();
        cout << x << " ";
        s.push(x);
        print(s,--num);
    }
    

    Good Luck

提交回复
热议问题