javaarrayslinked-listreverse

Reverse LinkedList in java


I need to understand simple example

 LinkedList list = new LinkedList();
        list.add("J");
        list.add("A");
        list.add("V");
        list.add("A");

I have simple LinkedList and need pass it to method reverse

public void reverse(LinkedList list) {

}

which will return reversed new list

and I do not need any ArraysUtils for reversing it

what is the short and practice way for having reversed output.

The same needed understand also for simple arrays.


Solution

  • public void reverse(LinkedList list) {
        //run till middle and swap start element with end element and so on
        for(int i = 0, mid = list.size()/2, j = list.size() - 1; i < mid; i++, j--)
            list.set(i, list.set(j, list.get(i)));//swap
    }
    

    Note: List.set(..,..) method returns the element previously at the specified position