我试图用递归找到最长的字符串,虽然我得到了正确的答案,但我不确定我的方法是否是递归的。我的主目录中有一个链表,我需要找到最长的链表。我的字符串最大的方法是“递归”
import java.util.LinkedList;
public class MyLinkedList extends LinkedList<String> {
public static String max="";
public static void main(String[] args) {
// TODO Auto-generated method stub
MyLinkedList myLinkedList = new MyLinkedList();
myLinkedList.add("Sarah");
myLinkedList.add("Barbara");
myLinkedList.add("Tom");
myLinkedList.add("George");
String largest = myLinkedList.findLargestStarter();
String largest1= largest( myLinkedList,0, 1);
System.out.println("Largest "+largest1);
System.out.println("max "+max);
}
public String findLargestStarter()
{
//largest=max;
return null;
}
public static String largest(MyLinkedList myLinkedList, int lowerIndex, int upperIndex)
{
if(lowerIndex == upperIndex) //the size of the sublist // is 1
max= myLinkedList.get(lowerIndex);
else
{
max = largest(myLinkedList, lowerIndex + 1, upperIndex);
if( myLinkedList.get(lowerIndex).length() > myLinkedList.get(upperIndex).length())
max= myLinkedList.get(lowerIndex);
else
max= myLinkedList.get(upperIndex);
}
// System.out.println(max);
return max;
}
}