题解 | #链表相加(二)#

链表相加(二)

https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b

/**
 * struct ListNode {
 *  int val;
 *  struct ListNode *next;
 * };
 */
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 *
 * @param head1 ListNode类
 * @param head2 ListNode类
 * @return ListNode类
 */

struct ListNode* reverseList(struct ListNode* head, int* l) {
    if (head == NULL) return NULL;
    struct ListNode* p = NULL;
    struct ListNode* c = head;
    while (c != NULL) {
        struct ListNode* n = c->next;
        c->next = p;
        p = c;
        c = n;
        (*l)++;
    }
    return p;
}

struct ListNode* addInList(struct ListNode* head1, struct ListNode* head2 ) {
    // write code here
    if (head1 == NULL) return head2;
    if (head2 == NULL) return head1;
    int l1 = 0, l2 = 0;
    struct ListNode* r1 = reverseList(head1, &l1);
    struct ListNode* r2 = reverseList(head2, &l2);
    // printf("length of l1 %d\nlength of l2 %d\n", l1, l2);
    if (l2 > l1) {
        struct ListNode* t = r2;
        r2 = r1;
        r1 = t;
        int tl = l2;
        l2 = l1;
        l1 = tl;
    }
    struct ListNode* head = r1;
    int carry = 0;
    while (l2 > 0) {
        int sum = r1->val + r2->val + carry;
        if (sum >= 10) {
            sum -= 10;
            carry = 1;
        } else {
            carry = 0;
        }
        r1->val = sum;
        r1 = r1->next;
        r2 = r2->next;
        l2--;
        l1--;
    }
    // printf("test\n");
    while (l1 > 0) {
        int sum = r1->val + carry;
        if (sum >= 10) {
            sum -= 10;
            carry = 1;
        } else {
            carry = 0;
        }
        r1->val = sum;
        if(l1 == 1) {
            if(carry == 1) {
                struct ListNode* one = malloc(sizeof(struct ListNode));
                one->val = 1;
                one->next = NULL;
                r1->next = one;
            }
        }
        r1 = r1->next;
        l1--;
    }
    r1 = reverseList(head, &l1);
    return r1;
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
11-24 20:55
阿里国际 Java工程师 2.7k*16.0
程序员猪皮:没有超过3k的,不太好选。春招再看看
点赞 评论 收藏
分享
10-09 09:39
门头沟学院 C++
HHHHaos:这也太虚了,工资就一半是真的
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务