Invert Elements in ArrayList<Integer> Java -
ok point of method invert elements in arraylist of type . if have elements:
5 6 7 8 9 10
once call method, position of elements should inverted such:
10 9 8 7 6 5
this method, advice appreciated :).
public void invertelements()     {         (int = list.size()-1; <= -1; i--)         {             int temp = list.get(i);             for(int j = 0; j < list.size()-1; j++)             {             list.set(j, temp);             }          }     } list name of arraylist.
update: tried way:
public void invertelements()     {         int index = 0;         (int = list.size()-1; > -1; i--)         {             int temp = list.get(i);             list.set(index, temp);             index++;             if(index == list.size()-1)             {                 break;             }          }     } which gives output: 10, 9, 8, 9, 10 explain me why?
you can take extremities of list @ each iteration , swap them :
arraylist<integer> list = new arraylist<>(arrays.aslist(1,2,3,4,5,6,7,8,9,10));     (int = 0; < list.size()/2; i++){                 int temp = list.get(i);                 int temp2 = list.get(list.size()-1-i);                 list.set(i, temp2);                 list.set(list.size()-1-i, temp);       }         for(integer : list)             system.out.print(i+"-"); gives output :
10-9-8-7-6-5-4-3-2-1-
at first iteration : temp = 1 / temp2 = 10 : swap them
 @ second iteration : temp = 2 / temp2 = 9 : swap them
and loop until go through elem of list size of list divided 2.
Comments
Post a Comment