题目:给你两个非空的链表,表示两个非负的整数。它们每位数字都是按照逆序的方式存储的,并且每个节点只能存储一位数字。请你将两个数相加,并以相同形式返回一个表示和的链表。你可以假设除了数字 0 之外,这两个数都不会以 0 开头。
**示例**:
算法:迭代O(n)—>两链表的数字对应相加。
class Solution {
public:
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) {
if (l1 == nullptr && l2 == nullptr) return nullptr;
ListNode* dummy = new ListNode(0);//虚拟头结点,方便找到新链表
ListNode* cur = dummy;//链接 新链表的指针
int sum = 0;//两链表对应结点相加的和
int carry = 0;//进位数(10为进制)
while (l1 != NULL || l2 != NULL)
{
int x = l1 != NULL ? l1->val : 0;//两整数相加,如果较短的链表到达NULL,则结点值为0与另一链表结点相加
int y = l2 != NULL ? l2->val : 0;
sum = x + y + carry;
if (sum >= 10)
{
carry = 1;//计算进位,大于十则进一位
}
else
{
carry = 0;
}
l1 = l1 != NULL ? l1->next : NULL;
l2 = l2 != NULL ? l2->next : NULL;
cur->next = new ListNode(sum % 10);//结点值为0 <= Node.val <= 9`,大于十则进一位
cur = cur->next;
}
if (carry == 1)//最高位相加大于十,还需进位 99+9=801
{
cur->next = new ListNode(1);
cur = cur->next;
}
cur->next=nullptr;//给新链表最后一个结点的next域添加NULL
return dummy->next;
}
};
int main()
{
Solution s;
//l1链表:2->4->3
struct Solution::ListNode* a = new struct Solution::ListNode(3);
struct Solution::ListNode* b = new struct Solution::ListNode(4, a);
struct Solution::ListNode* l1 = new struct Solution::ListNode(2, b);
//l2链表:5->6->4
struct Solution::ListNode* c = new struct Solution::ListNode(4);
struct Solution::ListNode* d = new struct Solution::ListNode(6, c);
struct Solution::ListNode* l2 = new struct Solution::ListNode(5, d);
struct Solution::ListNode* p = s.addTwoNumbers(l1, l2);
for (; p != NULL; p = p->next)
{
if (p->next == NULL)
{
cout << p->val;
break;
}
else
{
cout << p->val << "->";
}
}
}