/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
struct ListNode *p1,*p2;
struct ListNode *l3,*p3,*rear;
int c=0;
l3=(struct ListNode*)malloc(sizeof(struct ListNode));
l3->next=NULL;
p1=l1;
p2=l2;
rear=l3;
while (p1&&p2){
rear->val=(p1->val+p2->val+c)%10;
c=(p1->val+p2->val+c)/10;
if(p1->next&&p2->next){
p3=(struct ListNode *)malloc(sizeof(struct ListNode));
p3->next=NULL;
rear->next=p3;
rear=p3;
}else if(!p1->next&&!p2->next&&c){
p3=(struct ListNode *)malloc(sizeof(struct ListNode));
p3->next=NULL;
rear->next=p3;
rear=p3;
rear->val=c;
}
p1=p1->next;
p2=p2->next;
}
p3=p1?p1:p2;
if(p3){
rear->next=p3;
while (p3){
if((p3->val+c)>=10){
c=1;
p3->val=(p3->val+c)%10;
if(!p3->next){
p3->next=(struct ListNode *)malloc(sizeof(struct ListNode));
p3->next->next=NULL;
p3->next->val=c;
c=0;
}
}else{
p3->val+=c;
c=0;
}
p3=p3->next;
}
}
return l3;
}
从零开始的leetcode刷题——第2题
最新推荐文章于 2023-09-07 10:47:13 发布