力扣2. 两数相加

时间:2024-03-30 12:37:04
/** * 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: /** * * @param l1 Given linked list l1 * @param l2 Given linked list l2 * @return ListNode* */ ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode* p1 = l1; ListNode* p2 = l2; int carry = 0; ListNode* dummy = new ListNode(666); ListNode* tail = dummy; if (l1 == nullptr) { return l2; } if (l2 == nullptr) { return l1; } while (p1 != nullptr || p2 != nullptr) { int sum = 0; if (p1 != nullptr) { sum += p1 -> val; p1 = p1 -> next; } if (p2 != nullptr) { sum += p2 -> val; p2 = p2 -> next; } if (carry != 0) { sum += carry; } tail -> next = new ListNode(sum % 10); carry = sum / 10; tail = tail -> next; } //If carry is not equal to 0 if (carry != 0) { tail -> next = new ListNode(carry); } return dummy -> next; } };