标签:pre str turn span alt sum png nullptr src
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { int carry = 0; //进位 ListNode* dummyHead = new ListNode(-1); ListNode* curr = dummyHead; while (l1 != nullptr || l2 != nullptr || carry == 1) { int num1 = l1 != nullptr ? l1->val : 0; int num2 = l2 != nullptr ? l2->val : 0; int sum = carry + num1 + num2; ListNode* pNode = new ListNode(sum % 10); curr->next = pNode; curr = pNode; carry = sum / 10; if (l1 != nullptr) l1 = l1->next; if (l2 != nullptr) l2 = l2->next; } return dummyHead->next; } };
LeetCode 2. 两数相加 Add Two Numbers
标签:pre str turn span alt sum png nullptr src
原文地址:https://www.cnblogs.com/ZSY-blog/p/12922675.html