Leetcode—485.最大连续1的个数【中等】明天修改

2023每日刷题(十五)

Leetcode—2.两数相加

Leetcode—485.最大连续1的个数【中等】明天修改_第1张图片

迭代法实现代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    struct ListNode* lc = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* p = l1;
    struct ListNode* q = l2;
    lc->next = p;
    int c = 0;
    struct ListNode* p2 = p;
    struct ListNode* q2 = q;
    while(p&&q) {
        c = p->val + q->val + c;
        int tmp = c % 10;
        c /= 10;
        p->val = tmp;
        if(p->next == NULL) {
            p2 = p;
        }
        p = p->next; 
        q = q->next;
    }
    if(p) {
        while(p) {
            c = c + p->val;
            int tmp = c % 10;
            c /= 10;
            p->val = tmp;
            if(p->next == NULL) {
                p2 = p;
            }
            p = p->next;
        }
        if(c != 0) {
            struct ListNode* s = (struct ListNode*)malloc(sizeof(struct ListNode));
            s->val = c;
            s->next = NULL;
            p2->next = s;
            c = 0;
        }
    }
    
    if(q) {
        p2->next = q;
        while(q) {
            c = c + q->val;
            int tmp = c % 10;
            c /= 10;
            q->val = tmp;
            if(q->next == NULL) {
                q2 = q;
            }
            q = q->next;
        }
        if(c != 0) {
            struct ListNode* s = (struct ListNode*)malloc(sizeof(struct ListNode));
            s->val = c;
            s->next = NULL;
            q2->next = s;
            c = 0;
        }
    }

    if(c != 0) {
        struct ListNode* s = (struct ListNode*)malloc(sizeof(struct ListNode));
        s->val = c;
        s->next = NULL;
        p2->next = s;
        c = 0;
    }
    return lc->next;
}

之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!

你可能感兴趣的:(LeetCode刷题,leetcode,windows,linux)