2

I am trying to solve palindrome linked list on leetcode with brute force, but I am stuck in a logical problem. What's the difference between a head node and a reference to a head node?

class Solution {
    public boolean isPalindrome(ListNode head) {

        ListNode prev = null;
        ListNode current_head = head; // reference to head

        while (head != null) // reversing a linked list
        {
            ListNode next_node = current_head.next; // here is the error
            current_head.next = prev;
            prev = current_head;
            current_head = next_node;

        }
        while (prev != null && head != null) //trying to print values.
        {
            System.out.println("prev :" + prev.val);
            System.out.println(" head :" + head.val);
            head = head.next;
            prev = prev.next;
        }



        /*   while(prev != null  && current_head !=null)    //checking if it is a palindrome.
           {
              if(prev.val != current_head.val)
              {
                  return false;
              }
              else{
                    prev=prev.next;
               current_head= current_head.next;
              }
           }
        */

        return true;

    }
}

The error:

 WARNING: A command line option has enabled the Security Manager
    WARNING: The Security Manager is deprecated and will be removed in a future release
    java.lang.NullPointerException: Cannot read field "next" because "<local3>" is null
      at line 19, Solution.isPalindrome
      at line 54, __DriverSolution__.__helper__
      at line 84, __Driver__.main
khelwood
  • 55,782
  • 14
  • 81
  • 108
mario
  • 27
  • 4
  • 2
    Does this answer your question? [Avoiding NullPointerException in Java](https://stackoverflow.com/questions/271526/avoiding-nullpointerexception-in-java) – Jorge Campos Jan 28 '22 at 18:07
  • 2
    You could get that error / stack trace if `__DriverSolution__.__helper__` called your method with a `null` argument for `head` – Gus Jan 28 '22 at 18:12
  • You should loop while `current_head != null` and not while `head != null` in the first loop – vincrichaud Mar 23 '22 at 11:28

1 Answers1

0

you need to add a condition for current_head==null in your while loop that's faulty. It should work fine after that.

  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 20 '22 at 16:37