力扣 回文链表,我写的递归怎么是错的
資深大佬 : amiwrong123 9
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)