Recursive Java Solutions


  • 0
    M
    public class Solution {
        
        ListNode node;
        
        public boolean isPalindrome(ListNode head) {
            
            // if (head == null || head.next == null) return true;
            node = head;
            return isPalindromeUtil(head);
        }
        
        private boolean isPalindromeUtil(ListNode head) {
            
            if (head == null) {
                return true;
            }
            
            if (isPalindromeUtil(head.next)) {
                
                if (node.val == head.val) { //|| head == node) {
                    node = node.next;
                    return true;
                }
            }
            
            return false;
        }
    }
    

  • 0
    F

    I think the following statement is unnecessary, isPalindromeUtil() can handle it appropriately:

    if (head == null || head.next == null) return true;

    Also, for this:

    if (node.val == head.val || head == node)

    'head == node' is also unnecessary, when node.val == head.val is false, head will never be node. remove 'head == node', your code should work fine.


  • 0
    M

    @feng.wen.503 Thanks for pointing this out.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.