Java solution


  • 0
    M
    public class Solution {
      ListNode mainHead;
      boolean palindromCheckCompleted = false;
      public boolean isPalindrome(ListNode head) {
         mainHead = head;
         if(mainHead == null){
            return true;
         }
         if(mainHead.next == null){
            return true;
         }
        return checkPalindrom(head);
     }
    
    private boolean checkPalindrom(ListNode ptr) { 
        ListNode node = ptr;
        boolean isPalindrom = true;
        if(ptr.next != null) {
            ptr = ptr.next;
            isPalindrom = checkPalindrom(ptr);
        }
        if(palindromCheckCompleted){
            return true;
        }
        
        if(isPalindrom) {
            if(node.val == mainHead.val) {
                if(mainHead == node) {
                    palindromCheckCompleted = true;
                    return true;
                }
                mainHead = mainHead.next;
            }
            else {
                return false;
            }
        }
        else {
            return false;
        }
    
         return true;
    }

Log in to reply
 

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