使用listtiterator反转列表并跳过字符的特定位置(Java)



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

例如,字符串列表为["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]>

这些是我的错误。谢谢你的帮助/提示。

试试这个

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

最新更新