logo CodeStepByStep logo

switchPairs

Language/Type: C++ collections stack queue STL
Related Links:

Write a function named switchPairs that takes a reference to a stack of integers as a parameter and that switches successive pairs of numbers starting at the bottom of the stack. For example, if the stack initially stores these values:

{3, 8, 17, 9, 99, 9, 17, 8, 3, 1, 2, 3, 4, 14}

Your function should switch the first pair (3, 8), the second pair (17, 9), the third pair (99, 9), and so on, yielding this sequence:

{8, 3, 9, 17, 9, 99, 8, 17, 1, 3, 3, 2, 14, 4}

If there are an odd number of values in the stack, the value at the top of the stack is not moved. For example, if the original stack had stored:

{3, 8, 17, 9, 99, 9, 17, 8, 3, 1, 2, 3, 4, 14, 42}

It would again switch pairs of values, but the value at the top of the stack (42) would not be moved, yielding this sequence:

{8, 3, 9, 17, 9, 99, 8, 17, 1, 3, 3, 2, 14, 4, 42}

Do not make assumptions about how many elements are in the stack. Use one queue as auxiliary storage.

Function: Write a C++ function as described, not a complete program.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.