I'm working through a LeetCode problem with two linked lists that need to be added up.
It looks like my code is correctly generating a new list, with the expected nodes 7, and 9, followed by null, yet when I try to print out the results I'm running into an issue. I can see that the value of a->val is 7, but as soon as I get to the cout << a->val; line, it turns into another value.
Why is this happening?
using namespace std;
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) {}
};
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode ans;
ListNode* ptr = &ans;
int carry = 0;
while (l1 || l2) {
int a = 0;
int b = 0;
if (l1) {
a = l1->val;
l1 = l1->next;
}
if (l2) {
b = l2->val;
l2 = l2->next;
}
ptr->val = (a + b) % 10 + carry;
carry = (a + b) / 10;
if (l1 || l2) {
ptr->next = new ListNode();
ptr = ptr->next;
}
}
return &ans;
}
int main()
{
ListNode b(2);
ListNode c(7);
ListNode l1(2, &b);
ListNode l2(5, &c);
ListNode* a = addTwoNumbers(&l1, &l2);
while (a) {
cout << a->val;
a = a->next;
}
cout << endl;
}