该题不能使用简单的粗暴算法,对所有值进行整型相加,否则会出现值溢出。
解题方法:
/**
* 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)
{
//定义头节点和尾节点
ListNode * head = nullptr, *tail = nullptr;
//定义进位标识符
int carry = 0;
//当没有执行尾指针时
while (l1 || l2)
{
//如果不为空,则去当前值,为空则取0
int n1 = l1 ? l1->val : 0;
int n2 = l2 ? l2->val : 0;
//将两数之和相加,还需要加上进位符
int value = n1 + n2 + carry;
//当头节点不为空,令头节点等于尾节点,初始化节点
if (!head)
{
head = tail = new ListNode(value % 10);
}
else
{
//为尾节点赋值,并指向下一个节点
tail->next = new ListNode(value % 10);
tail = tail->next;
}
//进位符计算
carry = value / 10;
//当不为空时执行下一个节点
if (l1)
{
l1 = l1->next;
}
if (l2)
{
l2 = l2->next;
}
}
//最高位数相加大于0时
if (carry > 0)
{
tail->next = new ListNode(carry);
}
//返回头节点
return head;
}
};