【问题标题】:Reverse a list using ListIterator and skip certain position of character (Java)使用 ListIterator 反转列表并跳过字符的某些位置(Java)
【发布时间】:2021-10-24 08:05:26
【问题描述】:

我有一个任务要求我打印出给定的字符串列表,每隔一个字符串就跳过一次。然后,以相反的顺序打印字符串列表,每隔一个字符串跳过一次。所有输出应打印在同一行。

例如,如果字符串列表是 ["a", "b", "c", "d"],则输出应该是 "acdb"。如果字符串列表是 ["a", "b", "c"],则输出应该是 "acca"。

import java.util.List;
import java.util.ListIterator;

public class ListPrintStrings {
public static void printStrings(List<String> strings) {
        // write your code here
        ListIterator<String> stringWithIterator = strings.listIterator(strings.size());
        
        while(stringWithIterator.nextIndex() == 1){
            stringWithIterator.next();
            stringWithIterator.remove();
        }
        for(String s: strings){
            System.out.print(s);
        }
    }
}

我不知道如何使用 ListIterator 反转列表以及如何将字符串一起返回

Failures (3):
=> org.junit.ComparisonFailure: The ArrayList had an odd number of elements. Check that your solution can handles an odd number of elements. expected:<a[ceeca]> but was:<a[bcde]>
=> org.junit.ComparisonFailure: expected:<a[cdb]> but was:<a[bcd]>
=> org.junit.ComparisonFailure: expected:<hello[learningisfunjavaworld]> but was:<hello[worldlearningjavaisfun]>

这些是我的错误。感谢任何帮助/提示。

【问题讨论】:

    标签: java list collections iterator


    【解决方案1】:

    试试这个。

    public static void printStrings(List<String> strings) {
        ListIterator<String> i = strings.listIterator();
        while (i.hasNext()) {
            System.out.print(i.next());
            if (i.hasNext())
                i.next();
        }
        while (i.hasPrevious()) {
            System.out.print(i.previous());
            if (i.hasPrevious())
                i.previous();
        }
        System.out.println();
    }
    
    public static void main(String[] args) {
        printStrings(List.of("a", "b", "c", "d"));
        printStrings(List.of("a", "b", "c"));
    }
    

    输出:

    acdb
    acca
    

    【讨论】:

    • 我在运行此代码时出错。 org.junit.ComparisonFailure: The ArrayList had an odd number of elements. Check that your solution can handles an odd number of elements. expected:&lt;[ace]eca&gt; but was:&lt;[]eca&gt;org.junit.ComparisonFailure: expected:&lt;[ac]db&gt; but was:&lt;[]db&gt;org.junit.ComparisonFailure: expected:&lt;[hellolearningis]funjavaworld&gt; but was:&lt;[]funjavaworld&gt;。我应该使用System.out.print,但我不能在你提供的代码中这样做。
    • 您介意解释一下 hasPervious while 循环的作用吗?
    • 我不知道为什么会打印这样的消息。我的代码不使用 JUnit 或 ArrayList。
    • 在第一个while循环结束时,迭代器指针位于字符串的末尾。每次在第二个 while 循环中执行 previous() 时,迭代器指针都会后退一步。 hasPrevious() 到达字符串开头时返回 false。
    猜你喜欢
    • 2018-10-14
    • 1970-01-01
    • 2016-12-07
    • 2010-09-30
    • 1970-01-01
    • 2017-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多