gpt4 book ai didi

java - 左右旋转列表

转载 作者:太空宇宙 更新时间:2023-11-04 12:56:19 24 4
gpt4 key购买 nike

我正在考虑从列表中获取下一个和上一个元素,但是我无法正确处理这个问题 - 问题发生在列表的限制上。也许有人有更好的概念来解决这个问题?

public class Test {

private char heading = 'N';
List<Character> cardinal = Arrays.asList('N', 'E', 'S', 'W' );
ListIterator<Character> iterator = cardinal.listIterator();

public static void main(String[] args) {

Test test = new Test();
System.out.println("heading = " + test.heading);

test.rotateLeft(); System.out.println("Rotating left...");
System.out.println("heading = " + test.heading);
test.rotateLeft(); System.out.println("Rotating left...");
System.out.println("heading = " + test.heading);
}

public void rotateRight() {
this.heading =
(iterator.hasNext() ? iterator.next() : cardinal.get(0));
}

public void rotateLeft() {
this.heading =
(iterator.hasPrevious() ? iterator.previous() : cardinal.get(3));
}

}

最佳答案

问题在于,当到达列表末尾时,您不会重置迭代器。从那时起,iterator.hasNext() 将始终返回 false。一个简单的修复:

public void rotateRight() {
if (!iterator.hasNext())
iterator = cardinal.listIterator();
this.heading = iterator.next();
}

public void rotateLeft() {
if (!iterator.hasPrevious())
iterator = cardinal.listIterator(cardinal.size());
this.heading = iterator.previous();
}

如果您的列表是最终,它会变得更加容易:

int index = 0;

public void rotateRight() {
index = (index + 1) % cardinal.size();
this.heading = cardinal.get(index);
}

public void rotateLeft() {
index = (index - 1 + cardinal.size()) % cardinal.size();
this.heading = cardinal.get(index);
}

关于java - 左右旋转列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35351855/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com