https://leetcode-cn.com/problems/palindrome-linked-list/solution/hui-wen-lian-biao-by-leetcode/
官方答案递归:
class Solution {
private ListNode frontPointer;
private boolean recursivelyCheck(ListNode currentNode) {
if (currentNode != null) {
if (!recursivelyCheck(currentNode.next)) return false;
if (currentNode.val != frontPointer.val) return false;
frontPointer = frontPointer.next;
}
return true;
}
public boolean isPalindrome(ListNode head) {
frontPointer = head;
return recursivelyCheck(head);
}
}
我写的感觉执行过程是一样的啊,看懵了,大佬们帮忙看看。
class Solution {
private ListNode frontPointer;
private boolean recursion(ListNode currentNode){
if (currentNode.next == null){
return true;
}
if (!recursion(currentNode.next))
return false;
boolean result = frontPointer.val == currentNode.val;
frontPointer = frontPointer.next;
return result;
}
public boolean isPalindrome(ListNode head) {
frontPointer = head;
return recursion(head);
}
}
输入: [1,2] 输出: true 预期结果: false
1
amiwrong123 OP 刚发完贴就发现,自己哪里错了。。。if (currentNode.next == null)应该是 if (currentNode== null)。
|