これについて何か助けていただければ幸いです。プログラミングの学生 1 年生で、これは再帰を調べるための宿題です。1. 配列リストを再帰的に構築する必要がありました (以下で実行し、最小の問題に取り組み、次にそれ以上)。動作している)、arraylist を再帰的に反転するメソッドを作成し、それを ListMethodRunner テストに含めます。これは私が立ち往生しているところです。「list = reverseList(list.remove(0));」でエラーが発生している以下のコードを含めました。reverseList メソッドで。私が間違っている提案はありますか?
//List Methods import java.util.*;
public class ListMethods
{
//new method that produces an array list of integers (tempList) based on input of int n
public static ArrayList<Integer> makeList(int n)
{
ArrayList<Integer> tempList = null;
if (n <= 0) // The smallest list we can make
{
tempList = new ArrayList<Integer>(); // ceate the list tempList
return tempList; //return blank list for this if statement
}
else // All other size lists are created here
{
tempList = makeList(n-1); //recursively go through each variation of n from top down, when reach 0 will create the list
tempList.add(n); // program will then come back up through the variations adding each value as it goes
}
return tempList; //return the tempList population with all the variations
}
//create a copy of the values in the array list (tlist) and put it in (list)- used in next method
public static ArrayList<Integer> deepClone(ArrayList<Integer> tList)
{
ArrayList<Integer> list = new ArrayList<Integer>();
for (Integer i : tList)
{
list.add(new Integer(i));
}
return list;
}
//method that creates arraylist
public static ArrayList<Integer> reverseList(ArrayList<Integer> tList)
{
ArrayList<Integer> list = ListMethods.deepClone(tList);
if (list.size()<=1) // The list is empty or has one element
{
return list;// Return the list as is – no need to reverse!
}
else
{
list = reverseList(list.remove(0)); //recurse through each smaller list
//removing first value until get to 1 and will create list above
list.add(0);
// Use the solution to a smaller version of the problem
// to solve the general problem
}
return list;
}
}
//List Methods Runner
import java.util.ArrayList;
public class ListMethodsRunner
{
public static void main(String[] args)
{
ArrayList<Integer> tempList = ListMethods.makeList(100);
if (tempList.size() == 0)
{
System.out.println("The list is empty");
}
else
{
for (Integer i : tempList)
{
System.out.println(i);
}
}
}
}