In: Computer Science
/**
* Write a recursive function that accepts a stack of integers and
* replaces each int with two copies of that integer. For example,
* calling repeatStack and passing in a stack of { 1, 2, 3} would change
* the stack to hold { 1, 1, 2, 2, 3, 3}. Do not use any loops. Do not use
* any data structures other than the stack passed in as a parameter.
* @param stack
*/
public static void repeatStack(Stack<Integer> stack) {}
import java.util.Stack; public class RepeatStack { /** * Write a recursive function that accepts a stack of integers and * <p> * replaces each int with two copies of that integer. For example, * <p> * calling repeatStack and passing in a stack of { 1, 2, 3} would change * <p> * the stack to hold { 1, 1, 2, 2, 3, 3}. Do not use any loops. Do not use * <p> * any data structures other than the stack passed in as a parameter. * * @param stack */ public static void repeatStack(Stack<Integer> stack) { if (!stack.isEmpty()) { int num = stack.pop(); repeatStack(stack); stack.push(num); stack.push(num); } } public static void main(String[] args) { Stack<Integer> stack = new Stack<>(); stack.push(1); stack.push(2); stack.push(3); System.out.println("Original stack: " + stack); repeatStack(stack); System.out.println("Modified stack: " + stack); } }