-2
public class Solution {
public TreeNode sortedListToBST(ListNode head) {
    if (head == null)
        return null;
    if (head.next == null)
        return new TreeNode (head.val);
    ListNode slow = head;
    ListNode fast = head;
    ListNode pre = null;
    ListNode mid = null;
    while (fast.next != null && fast != null){
        pre = slow;
        fast = fast.next.next;
        slow = slow.next;
    }
    mid = slow;
    pre.next = null;
    TreeNode root = new TreeNode(slow.val);
    root.right = sortedListToBST(mid.next);
    root.left = sortedListToBST(head);

    return root;
}

}

This is my solution but it shows: java.lang.NullPointerException

when i change while (fast.next != null && fast != null){ to while (fast != null && fast.next != null){ the solution is accepted

i don't know the differences between them.

catworm
  • 3
  • 1
  • 2
    `while (fast.next != null && fast != null){` will cause **NullPointerException** when `fast` is null,that's the reason – flyingfox Dec 19 '18 at 09:30
  • 1
    when you check two conditions with &&, the following rule applies: If the first check results in false, the second (or all other) condition(s) won't be checked anymore. – Chris Dec 19 '18 at 09:31
  • @Ole VV,I am typing the answer and found you close it,oh no – flyingfox Dec 19 '18 at 09:32
  • 1
    @OleV.V. What I want to say is that I lost a chance to earn reputation,nothing else – flyingfox Dec 19 '18 at 09:35

1 Answers1

0

It is how && operator works... if there is a condition (cond1 && cond2), compiler will check if cond1 is true.. if it is false it wont check for second condition.. it will check for 2nd condition only if 1st one is true.. in your case.. if fast is null.. fast.next will give null pointer... so you should always check if fast is null before checking fast.next...

karthik manchala
  • 13,492
  • 1
  • 31
  • 55