I getting java.lang.IndexOutOfBoundsException in Linkedlist program to print consecutive largest and Smallest numbers in a LinkedList. example- input-
8
1 2 3 4 5 6 7 8
the output should be-
8 1 7 2 6 3 5 4
import java.util.LinkedList;
 import java.util.Scanner;
 
 class fr
 {
 public static void main(String args[])
     {
         Scanner sc=new Scanner(System.in);
         int n= sc.nextInt(),i,j,max,min,imax=0,imin=0,x;
         int size=n;
         LinkedList<Integer> arr = new LinkedList<Integer>();
         for(i=0;i<n;i++)
         {
             arr.add(sc.nextInt());
         }
         max=arr.get(0);
         min=arr.get(0);
             for(i=0;i<n;i++)
             {
                 x=arr.size();
                 for(j=0;j<x;j++)
                 {
                     if(arr.get(j)>max)
                     {
                         max=arr.get(j);
                         imax=j;
                     }
                     if(arr.get(j)<min)
                     {
                         min=arr.get(j);
                         imin=j;
                     }
                     
                 }
                 arr.remove(imax);
                 arr.remove(imin);
                 System.out.print(max+" "+min+" ");
             }
             
         }   
     }
Output window ---
8
1 2 3 4 5 6 7 8
8 1 Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 7, Size: 6
    at java.base/java.util.LinkedList.checkElementIndex(LinkedList.java:559)
    at java.base/java.util.LinkedList.remove(LinkedList.java:529)
    at fr.main(fr.java:36)
 
    