• 请不要在回答技术问题时复制粘贴 AI 生成的内容
amiwrong123
V2EX  ›  程序员

力扣 回文链表,我写的递归怎么是错的

  •  
  •   amiwrong123 · Oct 18, 2020 · 1309 views
    This topic created in 2035 days ago, the information mentioned may be changed or developed.

    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

    amiwrong123
        1
    amiwrong123  
    OP
       Oct 18, 2020
    刚发完贴就发现,自己哪里错了。。。if (currentNode.next == null)应该是 if (currentNode== null)。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1229 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 17:42 · PVG 01:42 · LAX 10:42 · JFK 13:42
    ♥ Do have faith in what you're doing.