gpt4 book ai didi

java - 从另一个类调用递归方法来反转链表

转载 作者:行者123 更新时间:2023-12-01 12:30:48 25 4
gpt4 key购买 nike

我目前有 2 个类,Images 和 ImageNode。在 ImageNode 类中,我有一个递归方法来反转链表。我相信我的代码对于该方法是正确的,但是我对如何在 Images 类中调用此方法感到困惑。

ImageNode方法---

 public ImageNode reverseUsingPrevious(ImageNode previous) {
if(previous == null) return previous;

ImageNode next = previous.getNext();

if(next == null) return previous;

previous.setNext(null);
ImageNode rev = reverseUsingPrevious(next);
next.setNext(previous);
return rev;
}

图片法----

private void reverseRec() {
cursor.reverseUsingPrevious(head);
//the cursor is the currently selected image(node), head is the start of the linked list
}

我不是 100% 确定应该将什么解析为reverseUsingPrevious 方法。

最佳答案

通过在 cursor.reverseUsingPrevious(head); 之前添加 head = 来更新头部。

额外提示:

尽管方法 reverseUsingPrevious 可能按原样工作,但它根本不会调用本地对象上的任何方法或变量(除了对 reverseUsingPrevious 的调用之外) ),所以它也可以是静态的。

但您可以删除参数(ImageNode previous),而不是将其设为静态,并将previous 的每个实例替换为this

现在,您不再调用 reverseUsingPrevious(node),而是将节点放在前面:node.reverseUsingPrevious()

关于java - 从另一个类调用递归方法来反转链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25930902/

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