leetcode problem: You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
struct ListNode *head = malloc(sizeof(struct ListNode));
head->next = NULL;
struct ListNode *temp = head;
int carry = 0;
int x, y;
while (l1 != NULL || l2 != NULL || carry != 0) {
temp->next = malloc(sizeof(struct ListNode));
int sum = (l1 != NULL ? l1->val : 0) + (l2 != NULL ? l2->val : 0) + carry;
// if (l1 != NULL) x = l1->val;
// if (l2 != NULL) y = l2->val;
// int sum = x + y + carry;
temp->next->val = (sum % 10);
carry = sum / 10;
temp->next->next = NULL;
temp = temp->next;
if (l1 != NULL) l1 = l1->next;
if (l2 != NULL) l2 = l2->next;
}
temp->next = NULL;
return (head->next);
}
This is my code and It was able to be passed. However, If I use variables x and y to get a sum of l1->val and l2->val-commenting "int sum = (l1 != NULL ? l1->val : 0) + (l2 != NULL ? l2->val : 0) + carry;" this part out , like
// if (l1 != NULL) x = l1->val;
// if (l2 != NULL) y = l2->val;
// int sum = x + y + carry;
or
x = l1 != NULL ? l1->val : 0;
y = l2 != NULL ? l2->val : 0;
It causes a time limit exceeded error. Can anyone please explain what is wrong?