I'm trying to solve the following problem:
Palindrome Linked List
Given the
head ofa singly linked list, returntrueif it is a palindrome.Input:
head = [1,2,2,1]Output:
true
I'm getting a wrong result for the following test case:
[1,1,2,1]
Expected output is false, but my code returns true (screenshot)
My code:
class Solution {
public ListNode reverseRecursive(ListNode head)
{
if (head == null || head.next == null)
{
return head;
}
ListNode newHead = reverseRecursive(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
public boolean isPalindrome(ListNode head) {
ListNode head1=reverseRecursive(head);
ListNode curr = head;
ListNode curr1 = head1;
while (curr != null && curr1 != null)
{
if(curr.val == curr1.val)
{
curr = curr.next;
curr1 = curr1.next;
} else {
return false;
}
}
return true;
}
}
I have used recursion to reverse the array and then compare the nodes of the linked list one by one, traversing through the list.
Class ListNode defined as follows:
public static class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}