I am working on recursion, in this case... I need sum all values of one stack. I have two functions, but only work with 10000 records. I need min one millon. Help me, please!
Code:
public static void main(String[] args) {
Recursion r = new Recursion();
Stack<Integer> stack = new Stack();
Random rnd = new Random();
int stack_size = 10000;
for (int i = 0; i < stack_size; i++) {
stack.push(rnd.nextInt(10 - 1));
}
int s = r.stack2(stack, 0);
//int s = r.stack1(stack, stack_size, 0, 0);
System.out.println("Sum = " + s);
}
public int stack2(Stack<Integer> stack, int sum) {
if (stack.size() > 1) {
sum += (stack.get(0) + stack.get(1));
stack.remove(stack.get(0));
stack.remove(stack.get(0));
return stack2(stack, sum);
} else {
return sum;
}
}
public int stack1(Stack<Integer> stack, int size, int i, int sum) {
if (i < size) {
i++;
sum = sum + stack.get(i - 1);
return stack1(stack, size, i, sum);
} else {
return sum;
}
}
popmethod ofStackinstead of the weird indexing.