In: Computer Science
Exercise 1
Modify the List class of Figure 21.3 in the textbook to include a method that recursively searches a linked-list for a specified value. Ensure that the name of your method includes your last name. The method must return a reference to the value if it is found; otherwise, it must return null. Use your method in a test program that creates a list of integers. The program must prompt the user for a value to locate in the list.
My code... but not putting out the right output needed
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ListSearch {
public static <T> T search(List<T> list, T value, int index){
if(list == null || index == list.size())
return null;
if(value.equals(list.get(index)))
return list.get(index);
return search(list, value, index+1);
}
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
System.out.println("Enter integers(-1 to stop): 4, 11, 32, 16, 77, 44, 33, 10, -1 ");
int num;
Scanner sc = new Scanner(System.in);
while(true){
num = sc.nextInt();
if(num == -1)
break;
list.add(num);
}
System.out.print("Enter integer to search: ");
int key = sc.nextInt();
Integer res = search(list, key, 0);
if(res == null)
System.out.println(key+" is not in list");
else
System.out.println(key+" is available in list");
}
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static <T> T search_mylastname(List<T> list, T
value, int index){//function name can be updated in all places to
the lastname if needed
if(list == null || index == list.size())
return null;
if(value.equals(list.get(index)))
return list.get(index);
return search_mylastname(list, value, index+1);
}
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
System.out.println("Enter integers(-1 to stop): ");
int num;
Scanner sc = new Scanner(System.in);
while(true){
num = sc.nextInt();
if(num == -1)
break;
list.add(num);
}
System.out.print("Enter integer to search: ");
int key = sc.nextInt();
Integer res = search_mylastname(list, key, 0);
if(res == null)
System.out.println(key+" is not in list");
else
System.out.println(key+" is available in list");
}
}
Screenshots:
The screenshots are attached below for reference.
Please follow them for output.
The errors in the given code are modified and the output is obtained as shown below.