Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 403
Armen Arzumanyan Avatar asked Aug 22 '26 11:08

Armen Arzumanyan


2 Answers

You can use the Collections class.

Collections.reverse(list);

Your list will be reversed after that operation.

like image 91
maba Avatar answered Aug 25 '26 00:08

maba


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

like image 41
vishal_aim Avatar answered Aug 25 '26 01:08

vishal_aim