给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。
请你将两个数相加,并以相同形式返回一个表示和的链表。
你可以假设除了数字 0 之外,这两个数都不会以 0 开头。
#include<bits/stdc++.h>
using namespace std;
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
struct ListNode* n=l1;
struct ListNode* m=l2;
struct ListNode* s=(struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* ss=s;
//依次相加
int a=0;
while(n!=NULL||m!=NULL){
int i1=0;
int j1=0;
int s1=0;
struct ListNode* r=(struct ListNode*)malloc(sizeof(struct ListNode));
if(n!=NULL){
i1=n->val;
}
if(m!=NULL){
j1=m->val;
}
s1=i1+j1+a;
if(s1<=9){
a=0;
r->val=s1;
}else{
s1=s1%10;
r->val=s1;
a=1;
}
r->next=NULL;
ss->next=r;
ss=ss->next;
if(n==NULL){
m=m->next;
continue;
}
if(m==NULL){
n=n->next;
continue;
}
n=n->next;
m=m->next;
}
if(a!=0){
struct ListNode* r=(struct ListNode*)malloc(sizeof(struct ListNode));
r->val=1;
r->next=NULL;
ss->next=r;
}
return s->next;
}
void printNode(struct ListNode* L){
struct ListNode* p = L;
while(p){
printf("%d\t",p->val);
p=p->next;
}
printf("\n");
}
struct ListNode* numToNode(int num){
struct ListNode *L=(struct ListNode*)malloc(sizeof(struct ListNode));;
struct ListNode *p=L;
int n =num;
if(n==0){
struct ListNode* r=(struct ListNode*)malloc(sizeof(struct ListNode));
r->val=0;
r->next=NULL;
return r;
}
while(n){
int last=n%10;
struct ListNode* r=(struct ListNode*)malloc(sizeof(struct ListNode));
r->val=last;
n/=10;
r->next=NULL;
p->next=r;
p=p->next;
}
return L->next;
}
int main(){
int n,m;
scanf("%d %d",&n,&m);
struct ListNode *L1=(struct ListNode*)malloc(sizeof(struct ListNode));;
struct ListNode *L2=(struct ListNode*)malloc(sizeof(struct ListNode));;
struct ListNode *L3=NULL;
L1 =numToNode(n);
L2 =numToNode(m);
L3 = addTwoNumbers(L1,L2);
printNode(L3);
return 0;
}