LeetCode2两数相加-C语言

给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。

如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。

您可以假设除了数字 0 之外,这两个数都不会以 0 开头。

示例:

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    struct ListNode *l3 = (struct ListNode *)malloc(sizeof(struct ListNode));
    struct ListNode *p1 = l1, *p2 = l2, *p3 = l3;
    p3 -> next = NULL;
    p3 -> val = 0;
    while(p1 != NULL && p2 != NULL){
        struct ListNode *node = (struct ListNode *)malloc(sizeof(struct ListNode));
        node -> val = 0;
        node -> next = NULL; 
        p3 -> next = node;
        p3 -> val += p1 -> val + p2 -> val;
        if(p3 -> val >= 10){
            p3 -> val -= 10;
            node -> val = 1;
        }
        p1 = p1 -> next;
        p2 = p2 -> next; 
        if(p1 == NULL && p2 == NULL && p3 -> next -> val == 0)
            {p3 -> next = NULL;}
        p3 = p3 -> next;
    }
    while(p1 != NULL){
        struct ListNode *node = (struct ListNode *)malloc(sizeof(struct ListNode));
        node -> val = 0;
        node -> next = NULL;
        p3 -> next = node;
        p3 -> val += p1 -> val; 
        if(p3 -> val >= 10){
            p3 -> val -= 10;
            node -> val = 1;
        }
        
        p1 = p1 -> next;
        if(p1 == NULL && p3 -> next -> val == 0)
            p3 -> next = NULL;
        p3 = p3 -> next;
    }
    while(p2 != NULL){
        struct ListNode *node = (struct ListNode *)malloc(sizeof(struct ListNode));
        node -> val = 0;
        node -> next = NULL; 
        p3 -> next = node;
        p3 -> val += p2 -> val;       
        if(p3 -> val >= 10){
            p3 -> val -= 10;
            node -> val = 1;
        }
        p2 = p2 -> next; 
        if(p2 == NULL && p3 -> next -> val == 0)
            p3 -> next = NULL;
        p3 = p3 -> next;
    }
    return l3;
}

 

你可能感兴趣的:(数据结构,C语言)