简体   繁体   English

使用 ListIterator,在 arraylist 中的 2 个偶数之间添加一个“-1”

[英]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.我正在做一个项目,我需要使用 ListIterator 遍历 arraylist 个整数。 Within this traversal, I will need to find all pairs of even numbers and add a "-1" in between to separate the evens.在此遍历中,我将需要找到所有偶数对并在其间添加“-1”以分隔偶数。 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我需要使用迭代器

You can use below code if you want -1 after two consecutive evens:如果你想在连续两个事件后得到-1 ,你可以使用下面的代码:

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:如果你想在两个连续的事件之间使用-1 ,你可以使用下面的代码:

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM