Advertisement
Guest User

Untitled

a guest
Sep 17th, 2019
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.23 KB | None | 0 0
  1. class Result{
  2.         public Result(ListNode node, boolean result){
  3.             this.result = result;
  4.             this.node = node;
  5.         }
  6.         public boolean result;
  7.         public ListNode node;
  8.     }
  9.    
  10.     private int getListLength(ListNode node){
  11.         int count = 0;
  12.         while(node != null){
  13.             count++;
  14.             node = node.next;
  15.         }
  16.         return count;
  17.     }
  18.    
  19.     public boolean isPalindrome(ListNode head){
  20.         int length = getListLength(head);
  21.         Result res = isPalindromRecursive(head, length);
  22.         return res.result;
  23.     }
  24.    
  25.     public Result isPalindromRecursive(ListNode head, int length){
  26.         //we reached the end of the first return nth element
  27.         if(head == null || length <= 0)
  28.             return new Result(head, true);
  29.         //the number of nodes in odd, return the next element
  30.         if(length == 1)
  31.             return new Result(head.next, true);
  32.        
  33.         Result res = isPalindromRecursive(head.next, length - 2);
  34.         if(!res.result || res.node == null){
  35.             return res;
  36.         }
  37.        
  38.         res.result = head.val == res.node.val;
  39.         res.node = res.node.next;;
  40.        
  41.         return res;
  42.     }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement