[英]reversing an integer listarray using recursion in java
希望對此有所幫助。 我是一年級編程的學生,這是研究遞歸的一項家庭作業。 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);
}
}
}
}
更換
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.