gpt4 book ai didi

Java:将元素从索引重新定位到链表的前面?

转载 作者:太空宇宙 更新时间:2023-11-04 14:08:51 25 4
gpt4 key购买 nike

我被这个问题困扰了很长一段时间。当我针对重新定位索引 1 的测试运行它时,我从 [A][B][C][D][E][B][B][C][D][E]。任何帮助将不胜感激。

public void moveToTop(int index) throws IllegalArgumentException {
if (index > size) {
throw new IllegalArgumentException();
}
if (index == 0) {
return;
} else {
Node ref = first;
for (int i = 1; i < index; i++) {
ref = ref.next;
}
Node temp = null;
temp = ref.next;
ref = temp.next;
temp = first;
first = temp;
}
}

最佳答案

void moveToTop(int index) {
// index should go until size - 1, not size
if (index >= size) throw new IllegalArgumentException();
// index == 0 should return the list unmodified
if (index == 0) return;

// We start in the head
// first = A -> B -> C -> D -> E
// ref = A -> B -> C -> D -> E
Node ref = first;
for (int i = 0; i < index - 1; i++) {
// And loop until we find the node before the one we want to move
// For index = 1, we won't loop, so ref is still equal to first
ref = ref.next;
}
// temp = A.next => temp = B
Node temp = ref.next;
// ref (A) is the node before the one we wish to move
// A.next = B.next => A.next = C => ref = A -> C -> D -> E
ref.next = temp.next;
// B.next = A => temp = B -> A -> C -> D -> E
temp.next = first;
// first = B -> A -> C -> D -> E
first = temp;
}

关于Java:将元素从索引重新定位到链表的前面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28574521/

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