445. 两数相加 II
难度中等155收藏分享切换为英文关注反馈
给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
进阶:
如果输入链表不能修改该如何处理?换句话说,你不能对列表中的节点进行翻转。
示例:
输入:(7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4) 输出:7 -> 8 -> 0 -> 7
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/*执行用时 :60 ms, 在所有 C++ 提交中击败了17.06%的用户
内存消耗 :71.2 MB, 在所有 C++ 提交中击败了11.11%的用户
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int len1=0,len2=0;
ListNode *h1=l1,*h2=l2;
while(h1!=NULL){
len1++;
h1=h1->next;
}
while(h2!=NULL){
len2++;
h2=h2->next;
}
int cha=len1-len2;
if(len1<len2){
cha*=-1;
h1=l2;h2=l1;}
else{h1=l1;h2=l2;}
vector<int> tmp;
while(cha--){
tmp.push_back(h1->val);
h1=h1->next;
}
while(h1!=NULL && h2!=NULL){
tmp.push_back(h1->val+h2->val);
h1=h1->next;
h2=h2->next;
}
int f=0;
for(int i=tmp.size()-1;i>=0;i--){
int carry=tmp[i]/10;
tmp[i]%=10;
if(carry>0){
if(i!=0) tmp[i-1]+=carry;
else f=carry;
}
}
ListNode *res=(len1>len2)?l1:l2;
res->val=tmp[0];
ListNode *p=res;
for(int i=1;i<tmp.size();i++){
res=res->next;
res->val=tmp[i];
}
if(f==0) return p;
else{
ListNode *t=new ListNode(f);
t->next=p;
return t;
}
return p;
}
};