我正在阅读一本编码书,并且难以理解解决方案以检查LinkedList是否是回文。LinkedList回文递归解决方案
提供的解决方案如下:
public class Result {
public LinkedListNode node;
public boolean result;
}
public Result isPalindromeRecurse(LinkedListNode head, int length) {
if (head == null || length == 0) {
return new Result(null, true);
} else if (length == 1) {
return new Result(head.next, true);
} else if (length == 2) {
return new Result(head.next.next, head.data == head.next.data);
}
Result res = isPalindromeRecurse(head.next, length - 2);
if (!res.result || res.node == null) {
return res;
} else {
res.result = head.data == res.node.data;
res.node = res.node.next;
return res;
}
}
public boolean isPalindrome(LinkedListNode head) {
Result p = isPalindromeRecurse(head, size);
return p.result;
}
我了解整个逻辑,在经过长-2可以让我们知道一旦我们已经达到了中间的元素,以帮助形成基本情况。然而,我很难想象除了基本情况比较以外,如何进行其他节点比较更接近中间元素。如果任何人都可以向我解释这一点,并帮助我通过代码和递归,我会很感激。
谢谢!我理解这一逻辑,但我仍然在努力将其反映在代码中。例如,如果我们的列表如下所示:1-> 2-> 3-> 4-> 5。我们按照以下顺序递归:isPalindromeRecurse(head.next,5),res = isPalindromeRecurse(head.next,3),res = isPalindromeRecurse(head.next,1)。后者运行第一,它已经是基本情况?那么会发生什么,res res = Result(head.next,true)?那么,什么?如果有人能够帮助我逐步理解它,我只是无法通过此代码。 –
您应该使用一个调试器并逐步执行代码,随时检查变量。 –