[leetcode]445. 两数相加 II

1.题目:
给定两个非空链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储单个数字。将这两数相加会返回一个新的链表。

示例:
输入: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
输出: 7 -> 8 -> 0 -> 7

2.代码:
思想:将两个链表反转实现对齐->之前的题型,最后再反转回来。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */

struct ListNode* reverseList(struct ListNode* l) {
    if(l==NULL||l->next==NULL)
        return l;
    struct ListNode* h=reverseList(l->next);
    l->next->next=l;
    l->next=NULL;
    return h;
}

struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    l1=reverseList(l1);
    l2=reverseList(l2);
    struct ListNode* p1=l1,*p2=l2;  
    struct ListNode* temp=(struct ListNode* )malloc(sizeof(struct ListNode));     
    temp->val=0;
    temp->next=p1;    
    int carry=0,sum=0;
    while(p1||p2||carry){  
        if(p1&&!p2){            
            sum=p1->val+carry;               
            carry=sum/10;
            p1->val=sum%10;  
            temp=p1;
            p1=p1->next;           
        }             
        if(p2&&!p1){
            temp->next=p2;
            p1=p2;
            p2=NULL;
            continue;
        }
        if(p1&&p2){
            sum=p1->val+p2->val+carry;
            carry=sum/10;
            p1->val=sum%10; 
            temp=p1;
            p1=p1->next;
            p2=p2->next;  
        }           
        if(!p1&&!p2&&carry){          
            struct ListNode* node=(struct ListNode* )malloc(sizeof(struct ListNode));   
            node->val=1;
            node->next=NULL;  
            temp->next=node;
            carry=0;
        }                   
    }  
    return reverseList(l1);   
    
}

3.知识点:

链表反转,两数相加。

猜你喜欢

转载自blog.csdn.net/MJ_Lee/article/details/88239945