Write a recursive function named stutter_stack
that takes an array stack of integers as a parameter and replaces every value in the stack with two occurrences of that value.
For example, suppose a stack named $s
stores these values, from bottom => top:
bottom [13, 27, 1, -4, 0, 9] top
Then the call of stutterstack($s)
should change the stack to store the following values:
bottom [13, 13, 27, 27, 1, 1, -4, -4, 0, 0, 9, 9] top
Notice that you must preserve the original order.
In the original stack the 9 was at the top and would have been popped first.
In the new stack the two 9s would be the first values popped from the stack.
If the original stack is empty, the result should be empty as well.
Constraints:
- Your solution must be recursive.
- Do not use any loops.
- Do not use any auxiliary collections or data structures to solve this problem.
A note about references in PHP: In order to write a function passes a parameter as
reference (thus modifying its state), you'll need to prepend "&" to the variable declaration
in the function header. For example, a function foo
that modifies the state
of an array parameter may be defined as:
function foo(&$arr) { ... }