In: Computer Science
**
* Write a recursive function that removes the first k even numbers
* from the stack. If there are less than k even elements in the stack,
* just remove all even elements. Do not use any loops or data structures
* other than the stack passed in as a parameter.
* @param stack
* @param k
* @return Returns the number of elements removed from the stack.
*/
public static int removeEvenNumbers(Stack<Integer> stack, int k) {
return 0;
}
import java.util.Stack; public class RemoveEven { public static int removeEvenNumbers(Stack<Integer> stack, int k) { if (!stack.empty()) { int num = stack.pop(), count = 0; boolean removed = false; if (num % 2 == 0 && k > 0) { k--; count++; removed = true; } count += removeEvenNumbers(stack, k); if (!removed) { stack.push(num); } return count; } return 0; } public static void main(String[] args) { Stack<Integer> stack = new Stack<>(); stack.push(3); stack.push(2); stack.push(7); stack.push(4); stack.push(1); System.out.println("Original stack: " + stack); int n = removeEvenNumbers(stack, 2); System.out.println("Modified stack: " + stack); System.out.println("Number of even numbers removed is " + n); } }