Search code examples
javaiteratorintegertraversal

Using a ListIterator, add a "-1" in between 2 even integers in an arraylist


So this is my first post so I apologize if it is not perfect. I am working on a project and I need to traverse an arraylist of integers with a ListIterator. Within this traversal, I will need to find all pairs of even numbers and add a "-1" in between to separate the evens. This is my code as of now:

 No two evens. Print the original list. If you find two even numbers then add a -1 between them. Print the new list.      
            */   
            ListIterator<Integer> lt5 = x.listIterator();
            System.out.println();
            System.out.println("N O E V E N S ");
            printArrays(x); 
            while(lt5.hasNext()) {
            if(lt5.next() %2 ==0 && lt5.next()%2==0) {
                lt5.previous();
                lt5.add(-1);
            }
            
            }
            
            System.out.println();
            ListIterator<Integer> lt6 = x.listIterator(); 
            while(lt6.hasNext()) {
                System.out.print(lt6.next()+" ");
            }

I am sure it is something simple but I can't figure it out. Any ideas on this?

I am required to use an iterator


Solution

  • You can use below code if you want -1 after two consecutive evens:

    public void modifyList(List<Integer> list){
        System.out.println(list);
        ListIterator<Integer> it = list.listIterator();
        while(it.hasNext()){
            if(it.next()%2==0 && it.hasNext() && it.next()%2==0){
                it.add(-1);
            }
        }
        System.out.println(list);
    }
    
    //Input: [1,2,3,4]
    //Output:[1,2,3,4]
    
    //Input: [1,2,4,5,6,8]
    //Output:[1,2,4,-1,5,6,8,-1]
    

    You can use below code if you want -1 between two consecutive evens:

    public void modifyList(List<Integer> list){
        System.out.println(list);
        ListIterator<Integer> it = list.listIterator();
        while(it.hasNext()){
            if(it.next()%2==0 && it.hasNext() && it.next()%2==0){
                it.previous();
                it.add(-1);
            }
        }
        System.out.println(list);
    }
    
    //Input: [1,2,3,4]
    //Output:[1,2,3,4]
    
    //Input: [1,2,4,5,6,8]
    //Output:[1,2,-1,4,5,6,-1,8]