logo CodeStepByStep logo

collectionMystery8

Language/Type: C++ collections Stack Queue
Author: Marty Stepp (on 2016/06/16)

Write the output produced by the following function when passed each of the following stacks: Note that a stack prints in {bottom ... top} order.

void collectionMystery8(Stack<int>& stack) {
    Queue<int> queue;
    Set<int> set;
    while (!stack.isEmpty()) {
        if (stack.peek() % 2 == 0) {
            queue.enqueue(stack.pop());
        } else {
            set.add(stack.pop());
        }
    }
    for (int n : set) {
        stack.push(n);
    }
    while (!queue.isEmpty()) {
        stack.push(queue.dequeue());
    }
    cout << stack << endl;
}
{1, 2, 3, 4, 5}
{3, 2, 7, 3, 3, 4, 1, 1, 4}
{9, 7, 14, 7, 22, 7, 3, 14}
{8, 5, 1, 2, 1, 1, 2, 1, 4, 5}

You must log in before you can solve this problem.


Log In

Need help?

If you do not understand how to solve a problem or why your solution doesn't work, please contact your TA or instructor.
If something seems wrong with the site (errors, slow performance, incorrect problems/tests, etc.), please

Is there a problem? Contact a site administrator.

© Marty Stepp, all rights reserved.