educative.io

Duplicate condition check&Edge cases

A reader asked us the following question:

I would really like to know why it doesn’t work to check p.next as opposed to p on line 389, which seems to be a repeated condition of the start of while loop. Besides, should an edge case be considered where a carry appears after adding up the ends of both lists, such as 365 + 824? Thanks for your support!

This is Alina from Educative.

First of all, let’s address the first part of the feedback:

“I would really like to know why it doesn’t work to check p.next as opposed to p on line 389, which seems to be a repeated condition of the start of while loop.”

The lines 389-392 are as follows:

    if p.next:
       p = p.next
    if q.next:
       q = q.next

These lines help us to iterate the two linked lists whose sum is being calculated. Suppose that the variable p is iterating over the linked list 5->6->3->None . Then, when p is the last node in the linked list, p.data and p.next will be 3 and None , respectively. Now, if we have the condition if p.next:, it will never be True as p.next will be None at this point. Therefore, the statement p = p.next will never execute. If that will be the case, p will never be None and the condition of the while loop will never become False . The same logic also applies to the statements regarding q . I hope this is clear enough.

Regarding the second part of the feedback, there is an assumption stated in the Exercise lesson which is as follows:

“Note that you will not be tested on numbers whose sum requires an additional digit.”

Hence, the edge case that the feedback is referring to is not necessary for the specified problem statement.

1 Like