How can I change a LinkedList from a void method (Java)

This seems very simple but I can’t quite figure out why this isn’t working.

I want to reverse the elements in my LinkedList which I have a working method for, but I can’t return the value as my prof wants it to be a void method. How would I go about this?

import java.util.LinkedList;
public class ListUtil {
    public static void reverse(LinkedList<String> strings) {
        LinkedList<String> reverseLinkedList = new LinkedList<>();
        for(int i = strings.size() - 1; i >= 0; i--) {
            reverseLinkedList.add(strings.get(i));
        }
        strings = reverseLinkedList;
        System.out.println(strings);
    }
}
import java.util.LinkedList;

public class ReverseTester {
    public static void main(String[] args) {
        LinkedList<String> employeeNames = new LinkedList<>();
        employeeNames.addLast("Dick");
        employeeNames.addLast("Harry");
        employeeNames.addLast("Romeo");
        employeeNames.addLast("Tom");
        
        ListUtil.reverse(employeeNames);
        System.out.println(employeeNames);
        System.out.println("Expected: [Tom, Romeo, Harry, Dick]");
    }
}

In my ListUtil class, it does reverse the list, but doesnt return a value (as it is void) but I don’t know how to go about setting employeeName in the ReverseTester class.

I know this is probably super simple but I have not been able to figure this out for the life of me, any help is greatly appreciated.

Answer

Empty and re-fill the existing list rather than replacing it.

public static void reverse(LinkedList<String> strings) {
    List<String> temp = new ArrayList<>(strings);   // Copy the contents of the original list. Pass the original list to constructor of our duplicate list.
    strings.clear();                                // Empty the original list.
    for (String e : temp)
        strings.addFirst(e);                        // Refill the original list using elements from our duplicate list.
}

Or simply

public static void reverse(LinkedList<String> strings) {
    Collections.reverse(strings);
}

Leave a Reply

Your email address will not be published. Required fields are marked *