0

对此有任何帮助将不胜感激。我是一年级编程学生,这是一个关于递归的家庭作业。1.我们必须递归地构建一个数组列表(在下面完成并针对最小的问题工作,然后更高) 2.使用线束测试它(也在下面) 3.然后我们必须制作数组列表的克隆副本(我认为正在工作)并编写一个方法来递归地反转数组列表并将其包含在 ListMethodRunner 测试中;这就是我卡住的地方。我在下面包含了我的代码,它在“list = reverseList(list.remove(0));”上引发了一个错误 在 reverseList 方法中。我哪里出错了有什么建议吗?

//列出方法 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);
     }
  }

     }
}
4

1 回答 1

3

代替

list = reverseList(list.remove(0))

list.remove(0);
list = reverseList(list);

ArrayList::remove(int)返回从列表中删除的元素。(Integer在这种情况下输入)

reverseList需要一个ArrayList<Integer>as 参数。因此错误。

您还必须在再次插入之前存储元素。您的代码应如下所示:

Integer num = list.remove(0);
list = reverseList(list); 
list.add(num);
于 2013-02-17T12:49:46.990 回答