Guolun Li
Guolun Li

Reputation: 87

Outputs get changed after removing one printing statement

#include <iostream>
 //Definition for singly-linked list.
 struct ListNode {
     int val;
     ListNode *next;
     ListNode() : val(0), next(nullptr) {}
     ListNode(int x) : val(x), next(nullptr) {}
     ListNode(int x, ListNode *next) : val(x), next(next) {}
 };

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
    {
        ListNode *final_ll;
        ListNode **ptr_final = &final_ll;
        int carry, sum;
        while (l1!=NULL || l2!=NULL || carry > 0)
        {
            int s1 = ((l1!=NULL) ? l1->val: 0);
            int s2 = ((l2!=NULL) ? l2->val: 0);
            sum = s1 + s2 + carry;
            carry = sum / 10;
            (*ptr_final) = new ListNode(sum % 10);
            //std::cout << "tenth_digit = " << carry << std::endl;
            std::cout << "unit_digit = " << sum % 10 << std::endl;
            if (l1!=NULL) l1 = l1->next;
            if (l2!=NULL) l2 = l2->next;
            ptr_final = &((*ptr_final)->next);
        }
        return final_ll;
    }
};
int main() {
    ListNode l1(9);
    ListNode l2(8, &l1);
    ListNode *result = Solution().addTwoNumbers(&l1, &l2);
}

This code outputs:

unit_digit = 5
unit_digit = 1
unit_digit = 1

However, when I uncomment

std::cout << "tenth_digit = " << carry << std::endl;

In Solution class, outputs are changed to:

tenth_digit = 3278
unit_digit = 4
tenth_digit = 328
unit_digit = 7
tenth_digit = 32
unit_digit = 8
tenth_digit = 3
unit_digit = 2
tenth_digit = 0
unit_digit = 3

A single printing statement should not change the number of iterations of the while loop and the value of unit_digit during each iteration. What's happening here?

Upvotes: 0

Views: 100

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 595837

Your code has undefined behavior.

In addTwoNumbers(), the final_ll and carry variables are both uninitialized, and both are being used before they have been assigned valid values.

carry holds a random value when declared, throwing off your while loop if that value is not 0.

If l1 and l2 were nullptr, and carry happened to be randomly <= 0, the body of the while loop would not be entered at all, causing addTwoNumbers() to return an indeterminate ListNode* value to the caller. And if carry were randomly > 0 instead, your while loop would run more times than you intend, skewing the results.

You need to initialize both variables, eg:

ListNode *final_ll = nullptr;
...
int carry = 0;

I would also suggest moving the declaration of sum inside the loop, since its value does not need to be preserved across loop iterations:

int carry = 0;
while (l1 || l2 || carry > 0)
{
    ...
    int sum = s1 + s2 + carry;
    ...
}

Upvotes: 2

Related Questions