如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 输出:7 -> 0 -> 8 原因:342 + 465 = 807 通过次数576,138提交次数1,499,041
力扣怎么突然这么人性化了?一道一道的出题,爷青回X2,这道题考的只是还是很简单的,链表的遍历与申请,还是比较容易想到的
/** * 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){ int n1=l1?l1->val:0; int n2=l2?l2->val:0; int sum=n1+n2+carry; if(!head){ head=tail=new ListNode(sum%10); } else{ tail->next=new ListNode(sum%10); tail=tail->next; } carry=sum/10; if(l1) l1=l1->next; if(l2) l2=l2->next; } if(carry) tail->next=new ListNode(carry); return head; } };