V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
amiwrong123
V2EX  ›  程序员

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

  •  
  •   amiwrong123 · 2020-10-18 22:06:58 +08:00 · 930 次点击
    这是一个创建于 1283 天前的主题,其中的信息可能已经有所发展或是发生改变。

    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
       2020-10-18 22:14:28 +08:00
    刚发完贴就发现,自己哪里错了。。。if (currentNode.next == null)应该是 if (currentNode== null)。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5182 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 01:19 · PVG 09:19 · LAX 18:19 · JFK 21:19
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.