In: Computer Science
Write a Java program/method that takes a LinkedList and returns a new LinkedList with the integer values squared and reversed. Example: if the LinkedList has (9, 5,4,6), then the returned list will have (36, 16,25,81). What is the time-complexity of your code? You must use listIterator for full credit.
public LinkedList getReverseSquaredList (LinkedList list) { }
Explanation:I have implemented the method getReverseSquaredList() and have also provided a main method to show the output of the program, please find the image attached with the answer.Please upvote if you liked my answer and comment if you need any modification or explanation.
The time complexity of the code is O(n) where n is the number of elements in the list.
//code
import java.util.LinkedList;
import java.util.ListIterator;
public class ReverseAndSquare {
public LinkedList<Integer>
getReverseSquaredList(LinkedList<Integer> list) {
LinkedList<Integer>
reversedList= new LinkedList<>();
ListIterator<Integer>
listIterator = list.listIterator(list.size());
while (listIterator.hasPrevious())
{
Integer element
= listIterator.previous();
reversedList.add(element * element);
}
return reversedList;
}
public static void main(String[] args) {
ReverseAndSquare reverseAndSquare =
new ReverseAndSquare();
LinkedList<Integer> list =
new LinkedList<>();
list.add(9);
list.add(5);
list.add(4);
list.add(6);
System.out.println("Before
reversing and squaring the list:");
System.out.println(list);
LinkedList<Integer>
reversedList = reverseAndSquare
.getReverseSquaredList(list);
System.out.println("After reversing
and squaring thelist:");
System.out.println(reversedList);
}
}
Output: