在这个任务中,我需要迭代和递归地遍历一个大小为1,000,000的链表。我已经完成了迭代部分,但对于递归部分我感到困惑。我已经理解了概念,但我告诉我的老师我不能用递归方式完成它,因为我肯定会遇到堆栈溢出错误。他说我不应该遇到那个问题,但我完全被卡住了。如果有任何提示,那将是很好的,因为我不知道我做错了什么。
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);
}
}
}