在java中使用递归来反转整数列表

时间:2013-02-17 12:39:55

标签: java recursion

感谢任何帮助。是第一年编程学生,这是一个看递归的家庭作业。 1.我们必须递归地建立一个arraylist(在下面完成并为最小的问题工作然后更高) 2.使用安全带(也在下方)进行测试 3.然后我们必须制作数组列表的克隆副本(我认为它正在工作)并编写一个方法来递归反转arraylist并将其包含在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);
     }
  }

     }
}

1 个答案:

答案 0 :(得分:3)

替换

list = reverseList(list.remove(0))

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

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

reverseList需要ArrayList<Integer>作为参数。因此错误。

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

Integer num = list.remove(0);
list = reverseList(list); 
list.add(num);