For this assignment given to me, I am supposed to move through a linked list of size 1,000,000 iteratively and recursively. I have the iterative part down but I am confused on the recursive part. I have the concept down but I have told my teacher that I cannot recursively do it because I will inevitably get a stack overflow error. He says I should not be getting that problem but I am totally stuck. Any tips would be great as I have no idea what I am doing wrong.
public static void main(String[] args) {
System.out.println("Please enter how many random numbers you want to generate: ");
Scanner prompt = new Scanner(System.in);
int amount = prompt.nextInt();
Random rnd = new Random();
System.out.println("Creating list...");
for (int i = 0; i < amount; i++) {
randomList.add(rnd.nextInt(100));
}
System.out.println("Going through list...");
iterateNumbers();
long startTimeRec = System.nanoTime();
recursiveNumbers(randomList);
long elapsedTimeRec = System.nanoTime() - startTimeRec;
double seconds = (double)elapsedTimeRec / 1000000000.0;
System.out.println("Recursively, the function took " + seconds + " seconds.");
prompt.close();
}
//create the linked list
public static LinkedList<Integer> randomList = new LinkedList<Integer>();
private static void iterateNumbers() {
long startTime = System.nanoTime();
for (int i = 0; i < randomList.size(); i++) {
randomList.remove();
}
long elapsedTime = System.nanoTime() - startTime;
double seconds = (double)elapsedTime / 1000000000.0;
System.out.println("Iteratively, the function took " + seconds + " seconds.");
}
private static void recursiveNumbers(LinkedList<Integer> current) {
if (current.isEmpty() == true) {
return;
} else {
current.removeFirst();
recursiveNumbers(current);
}
}
}
