美文网首页
445. Add Two Numbers II

445. Add Two Numbers II

作者: larrymusk | 来源:发表于2017-11-24 22:06 被阅读0次

    先对两个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);
        
    }

    相关文章

      网友评论

          本文标题:445. Add Two Numbers II

          本文链接:https://www.haomeiwen.com/subject/gmqqbxtx.html