/**
* 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:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
auto dummy = new ListNode (-1), cur = dummy;
int t = 0;
//模拟一遍加法
while(l1 || l2)
{
int n1 = l1 ? l1 -> val : 0;
int n2 = l2 ? l2 -> val : 0;
t += n1 + n2;
cur -> next = new ListNode(t % 10); // 记得申请节点来存数
cur = cur -> next;
t /= 10;
if(l1) l1 = l1 -> next;
if(l2) l2 = l2 -> next;
}
if(t) cur -> next = new ListNode (1); // 最后要特判是否要进位
return dummy -> next;
}
};
LeetCode 2. 两数相加
最新推荐文章于 2024-09-10 22:16:49 发布