【问题标题】:Using a ListIterator, add a "-1" in between 2 even integers in an arraylist使用 ListIterator,在 arraylist 的 2 个偶数之间添加“-1”
【发布时间】:2021-01-08 03:05:33
【问题描述】:

这是我的第一篇文章,如果不完美,我深表歉意。我正在做一个项目,我需要使用 ListIterator 遍历整数数组列表。在此遍历中,我需要找到所有偶数对并在其间添加“-1”以分隔偶数。这是我现在的代码:

 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()+" ");
            }

我确信这很简单,但我无法弄清楚。对此有何想法?

我需要使用迭代器

【问题讨论】:

    标签: java iterator integer traversal


    【解决方案1】:

    如果你想在两个连续的事件之后使用-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]
    

    如果您想在两个连续事件之间使用-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]
    

    【讨论】:

    • 我将如何在其中加入一个迭代器?我需要使用迭代器。
    • @HunterChristianDonahue,是的,看到了你的编辑。相应地修改了代码
    • 最后一行不是我们想要的;它应该是[1,2,4,-1,5,6,-1,8]。如果你的代码输出了那个(我没有测试过),那就有问题了。
    猜你喜欢
    • 2016-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-12
    • 1970-01-01
    相关资源
    最近更新 更多