對於賦予給我的這個賦值,我應該迭代並遞歸地遍歷一個大小爲1,000,000的鏈表。我有迭代的部分,但我對遞歸部分感到困惑。我有這個概念,但我告訴我的老師,我不能遞歸地這樣做,因爲我不可避免地會遇到堆棧溢出錯誤。他說我不應該得到這個問題,但我完全陷入困境。任何提示都會很棒,因爲我不知道我做錯了什麼。Java從鏈表遞歸中刪除一個元素
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);
}
}
}
你用這個c得到了什麼頌?你確切的問題是什麼? – innoSPG