Getting wrong answer for some test cases

/**

  • Definition for singly-linked list.
  • public class ListNode {
  • int val;
    
  • ListNode next;
    
  • ListNode() {}
    
  • ListNode(int val) { this.val = val; }
    
  • ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    
  • }
    */

class Solution {
private ListNode reverseList(ListNode head) {
if(head==null || head.next==null)
return head;

    ListNode prev=head;
    ListNode cur=prev.next;
    ListNode n= cur.next;
    
    while(cur.next!=null)
    {
        cur.next=prev;
        prev=cur;
        cur=n;
        n=n.next;
    }
    cur.next=prev;
    head.next=null;
    head=cur;
    return head;
}

public boolean isPalindrome(ListNode head) {
    
    if(head==null || head.next==null)
        return true;
    ListNode head1=head;
    ListNode rev=reverseList(head);
    
    while(head1!=null)
    {
        if(head1.val==rev.val)
        {
            head1=head1.next;
            rev=rev.next;
        }
        else
            return false;
    }
    return true;
    
}

}

this is the code and I’m getting wrong answer for list [1,1,2,1] but reverse function gives right answer for that list. what is wrong?

@Kapsime_S,

For reverse do:

    private ListNode reverseList(ListNode head) {
        ListNode curr = head;
        ListNode prev = null;
        ListNode next = null;
        
        while(curr != null) {
            next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }
        
        return prev;
    }

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.