I am doing coding with leetcode. For the question of Two add numbers, my solution could not be accepted because I didn't use new when creating struct. Here is my code:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
struct ListNode temp(-1);
struct ListNode *pre = &temp;
bool PlusOne = false;
int val1 = 0;
int val2 = 0;
int sum;
while (NULL != l1 || NULL != l2)
{
if (NULL != l1)
{
val1 = l1->val;
l1 = l1->next;
}
if (NULL != l2)
{
val2 = l2->val;
l2 = l2->next;
}
if (PlusOne == true)
{
sum = (val1 + val2 + 1) % 10;
PlusOne = (val1 + val2 + 1) / 10;
}
else
{
sum = (val1 + val2) % 10;
PlusOne = (val1 + val2) / 10;
}
struct ListNode newNode(sum);
pre->next = &newNode;
pre = &newNode;
val1 = 0;
val2 = 0;
}
if (true == PlusOne)
{
struct ListNode newNode(1);
pre->next = &newNode;
}
pre = temp.next;
return pre;}
It said runtime error, but it works if I use pre->next = new ListNode(1) replacing of struct ListNode newNode(1); pre->next = &newNode;
Is there anyone knows why?