https://leetcode-cn.com/problems/add-two-numbers/
代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int len1=0,len2=0;
vector<int> vec1,vec2;
while(l1!=NULL){
vec1.push_back(l1->val);
len1++;
l1=l1->next;
}
while(l2!=NULL){
vec2.push_back(l2->val);
len2++;
l2=l2->next;
}
reverse(vec1.begin(),vec1.end());
reverse(vec2.begin(),vec2.end());
int jw=0;
ListNode *l3=new ListNode(0),*p=new ListNode(0);
p=l3;
while(len1>0&&len2>0){
int key=vec1[len1-1]+vec2[len2-1]+jw;
if(key>=10){
key-=10;
jw=1;
}else{
jw=0;
}
ListNode *x=new ListNode(key);
p->next=x;
p=x;
p->val=key;
p->next=NULL;
len1--,len2--;
}
if(len1>0){
while(len1>0){
int key=vec1[len1-1]+jw;
if(key>=10){
key-=10;
jw=1;
}else{
jw=0;
}
ListNode *x=new ListNode(key);
p->next=x;
p=x;
p->val=key;
p->next=NULL;
len1--;
}
}
if(len2>0){
while(len2>0){
int key=vec2[len2-1]+jw;
if(key>=10){
key-=10;
jw=1;
}else{
jw=0;
}
ListNode *x=new ListNode(key);
p->next=x;
p=x;
p->val=key;
p->next=NULL;
len2--;
}
}
if(jw==1){
ListNode *x=new ListNode(jw);
p->next=x;
p=x;
p->val=1;
p->next=NULL;
}
return l3->next;
}
};
原文地址:https://www.cnblogs.com/zzh1582188532/p/12158939.html
时间: 2024-11-07 15:55:56