欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

力扣2. Add Two Numbers

程序员文章站 2023-12-26 17:30:21
...
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
    struct ListNode *pr=(struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode *p1=l1,*p2=l2,*p3=pr;
    int flag=0;
    while(p1!=NULL||p2!=NULL){
        struct ListNode *t=(struct ListNode*)malloc(sizeof(struct ListNode));
        pr->next=t;
        pr=t;
        if(p1!=NULL&&p2!=NULL)
            t->val=p1->val+p2->val;
        else if(p1!=NULL)
            t->val=p1->val;
        else if(p2!=NULL)
            t->val=p2->val;
        if(flag==1){
            t->val++;
            flag=0;
        }
        if(t->val>=10){
            t->val%=10;
            flag=1;
        }
        if(p1!=NULL)
            p1=p1->next;
        if(p2!=NULL)
            p2=p2->next;
    }
    
    if(flag==1){
        struct ListNode *t=(struct ListNode*)malloc(sizeof(struct ListNode));
        t->val=1;
        pr->next=t;
        pr=t;
    }
    pr->next=NULL;
    return p3->next;
    
}

上一篇:

下一篇: