美文网首页
2. Add Two Numbers

2. Add Two Numbers

作者: YellowLayne | 来源:发表于2017-06-14 10:05 被阅读0次

    1.描述

    You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

    You may assume the two numbers do not contain any leading zero, except the number 0 itself.

    Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
    Output: 7 -> 0 -> 8

    2.分析

    3.代码

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     struct ListNode *next;
     * };
     */
    struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
        struct ListNode* l = NULL;
        struct ListNode* p = NULL;
        struct ListNode* p1 = l1;
        struct ListNode* p2 = l2;
        int plus = 0;
        while (p1 != NULL && p2 != NULL) {
            struct ListNode* q = (struct ListNode*)malloc(sizeof (struct ListNode));
            q->val = (p1->val + p2->val + plus) % 10;
            q->next = NULL;
            plus = (p1->val + p2->val + plus) / 10;
            if (l == NULL) {
                l = p = q;
            }else {
                p->next = q;
                p = q;
            }
            p1 = p1->next;
            p2 = p2->next;
        }
        
        while (p1 != NULL) {
            struct ListNode* q = (struct ListNode*)malloc(sizeof (struct ListNode));
            q->val = (p1->val + plus) %10;
            q->next = NULL;
            plus = (p1->val + plus) / 10;
            p->next = q;
            p = q;
            p1 = p1->next;
        }
        
        while (p2 != NULL) {
            struct ListNode* q = (struct ListNode*)malloc(sizeof (struct ListNode));
            q->val = (p2->val + plus) %10;
            q->next = NULL;
            plus = (p2->val + plus) / 10;
            p->next = q;
            p = q;
            p2 = p2->next;
        }
        
        while (plus != 0) {
            struct ListNode* q = (struct ListNode*)malloc(sizeof (struct ListNode));
            q->val = plus % 10;
            q->next = NULL;
            plus = plus/10;
            p->next = q;
            p = q;
        }
        
        return l;
    }
    

    相关文章

      网友评论

          本文标题:2. Add Two Numbers

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