445. Add Two Numbers II

先对两个list 翻转后相加,然后把相加后的链表翻转返回

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode * reverse(struct ListNode *head)
{
    if(head == NULL || head->next == NULL)
        return head;
    
    struct ListNode * node = reverse(head->next);
    head->next->next = head;
    head->next = NULL;
    
    return node;
}
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    
    if(l1 == NULL)
        return l2;
    if(l2 == NULL)
        return l1;
    
    struct ListNode * rl1 = reverse(l1);
    struct ListNode * rl2 = reverse(l2);
    
    struct ListNode * dummy = calloc(1, sizeof(struct ListNode));
    struct ListNode *last = dummy;
    int carry = 0;
    int val = 0;
    while(1){
        
        if(rl1&&rl2){
            val = (rl1->val+rl2->val+carry)%10;
            carry = (rl1->val+rl2->val+carry)/10;
            rl1 = rl1->next;
            rl2 = rl2->next;
            
        }else if(rl1){
            val = (rl1->val+carry)%10;
            carry = (rl1->val+carry)/10;
            rl1 = rl1->next;
            
        }else if(rl2){
            val = (rl2->val+carry)%10;
            carry = (rl2->val+carry)/10;
            rl2 = rl2->next;
        }else
            break;
        
        struct ListNode *node = calloc(1, sizeof(struct ListNode));
        node->val = val;
        last->next = node;
        last = node;
    }
    
    if(carry){
        struct ListNode *node = calloc(1, sizeof(struct ListNode));
        node->val = 1;
        last->next = node;
        
    }
    
    struct ListNode * tmp = dummy->next;
    free(dummy);
    
    //tmp = reverse(tmp);
    
    //return tmp;
    return reverse(tmp);
    
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容