Use Java. Thank you! Write a class that provides the following three methods: It
ID: 3838798 • Letter: U
Question
Use Java. Thank you!
Write a class that provides the following three methods: Iteratively reverse a list public static LList iterativeReverseList (LList list) that accepts a reference to a LList and returns a reference to another LList that contains the data of the original list in reverse order. Your method should be implemented using iteration. 2. Recursively Reverse a list public static LList recursiveReverseList(LList list) that accepts a reference to a LList and returns a reference to another LList that contains the data of the original list in reverse order. Your method should be implemented using recursion. 3. Sort Using ArrayList public static ArrayList insertSort (ArrayList list) that accepts a reference to an ArrayLIst and returns another ArrayList that contains the data of the original list in ascending order. You can implement your method as insertion sort or selection sort. You cannot use the Java sort methods. Write a test claExplanation / Answer
Hi, I have answered Q3..
Since you have not posted LList<E> structure so I can not answer Q1 and Q2.
import java.util.ArrayList;
import java.util.Scanner;
public class InsertionSortList {
public static void insertionSortList(ArrayList<String> aryList, String element){
if(! aryList.contains(element)){
// edge case: Size one list, number coming in is smaller.
if(aryList.size() == 0 || aryList.get(0).compareTo(element) > 0) {
aryList.add(0, element);
} else if(aryList.get(aryList.size()-1).compareTo(element) < 0){
aryList.add(element);
}
else {
//System.out.println(element);
for(int i = 0; i < aryList.size()-1; i++) {
if(aryList.get(i).compareTo(element) < 0 && element.compareTo(aryList.get(i+1)) < 0) {
aryList.add(i+1, element);
break;
}
}
}
}
}
// Method to sort list ans return new sorted list
public static ArrayList<String> insertSort(ArrayList<String> aryList){
ArrayList<String> sortedList = new ArrayList<>();
for(String str :aryList)
insertionSortList(sortedList, str);
return sortedList;
}
public static void main(String[] args) {
ArrayList<String> aryList = new ArrayList<>();
Scanner sc = new Scanner(System.in);
System.out.print("Enter string to insert in list (quit to stop): ");
while(true){
String ele = sc.next();
if("quit".equalsIgnoreCase(ele))
break;
aryList.add(ele);
}
System.out.println(aryList);
ArrayList<String> sortedList = insertSort(aryList);
System.out.println(sortedList);
sc.close();
}
}
/*
Sample run:
Enter string to insert in list (quit to stop): pravesh
apple
bnana
cat
zebra
papaya
quit
[pravesh, apple, bnana, cat, zebra, papaya]
[apple, bnana, cat, papaya, pravesh, zebra]
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.