Recursion
Recursion for linked list
Java Solution 1
public boolean isPalindrome(ListNode head) {
return head == null || recurse (head, head) != null;
}
private ListNode recurse (ListNode node, ListNode head) {
if (node == null) return head;
ListNode res = recurse (node.next, head);
if (res == null) return res;
else if (res.val == node.val) return (res.next == null ? res : res.next);
else return null;
}
Java Solution 2
public class Solution {
public ListNode root;
public boolean isPalindrome(ListNode head) {
root = head;
return (head == null) ? true : _isPalindrome(head);
}
public boolean _isPalindrome(ListNode head) {
boolean flag = true;
if (head.next != null) {
flag = _isPalindrome(head.next);
}
if (flag && root.val == head.val) {
root = root.next;
return true;
}
return false;
}
}