0

While writing a code for finding the the middle of the linked List. I encounter a problem where I am not able to understand why one one the snipper works while other does not. Snippet Working

        ListNode *slow = head, *fast = head;
        while (fast && fast->next)
            slow = slow->next, fast = fast->next->next;
        return slow;

Snippet not working

        ListNode *slow = head, *fast = head;
        while (fast->next && fast)
            slow = slow->next, fast = fast->next->next;
        return slow;

Now in my understading, since we have a "&&" condition, it'll go inside the loop only when both the conditions are met, yet, the second snippet fails on some test cases. Thanks in advance.

AxRy
  • 13
  • 3
  • Talk us through what you’ve done to debug this code and what you’re seeing when you did. – templatetypedef Jun 24 '23 at 00:07
  • Well, Here is the question i am attempting https://www.codingninjas.com/codestudio/problems/973250?topList=striver-sde-sheet-problems&utm_source=striver&utm_medium=website Here, The first snipper is accepted without problem but the second one has errors in some test cases though I feel like both the codes are identical. I am trying to understand the difference between both the codes. – AxRy Jun 24 '23 at 00:37
  • Have you tried running the code on your own machine to see what happens in each case? You might notice what’s going on if you do. – templatetypedef Jun 24 '23 at 00:46

1 Answers1

0

The && is a short-circuit operator, so that the second operand is only evaluated when the first operand evaluates to a truthy value.

The correct code has this:

(fast && fast->next)

Which means that fast->next is only evaluated when fast is not a null pointer.

Now take the the other code:

(fast->next && fast)

Here fast->next is evaluated first before having verified that fast is not a null pointer. If fast is a null pointer, this represents an invalid de-referencing and the program will have undefined behaviour.

trincot
  • 317,000
  • 35
  • 244
  • 286