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

链表相加(二)

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

/**
 * struct ListNode {
 *  int val;
 *  struct ListNode *next;
 * };
 */
struct ListNode* ReverseList(struct ListNode* head);
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 *
 * @param head1 ListNode类
 * @param head2 ListNode类
 * @return ListNode类
 */
struct ListNode* addInList(struct ListNode* head1, struct ListNode* head2 ) {
    // write code here
    struct ListNode* h1, *h2, *head, *sum;
    struct ListNode init;
    // n: store the part over 10
    int n = 0;
    init.next = NULL;
    init.val = 0;
    sum  = &init;
    head = sum;
    h1 = ReverseList(head1);
    h2 = ReverseList(head2);
    while (h1 && h2) {
        struct ListNode* tmp = (struct ListNode*)malloc(sizeof(struct ListNode));
        tmp ->next = NULL;
        int m = h1->val + h2->val + n;
        if (m >= 10) {
            tmp->val = m - 10;
            n = 1;
        } else {
            tmp->val = m;
            n = 0;
        }
        sum->next = tmp;
        sum = sum->next;
        h1 = h1->next;
        h2 = h2->next;
    }
    while (h1) {
        struct ListNode* tmp = (struct ListNode*)malloc(sizeof(struct ListNode));
        //tmp->val = h1->val;
        int m = h1->val + n;
        if (m >= 10) {
            tmp->val = m - 10;
            n = 1;
        } else {
            tmp->val = m;
            n = 0;
        }
        tmp ->next = NULL;
        sum->next = tmp;
        sum = sum->next;
        h1 = h1->next;
    }
    while (h2) {
        struct ListNode* tmp = (struct ListNode*)malloc(sizeof(struct ListNode));
        //tmp->val = h2->val;
        int m = h2->val + n;
        if (m >= 10) {
            tmp->val = m - 10;
            n = 1;
        } else {
            tmp->val = m;
            n = 0;
        }
        tmp ->next = NULL;
        sum->next = tmp;
        sum = sum->next;
        h2 = h2->next;
    }
    if (n) {
        struct ListNode* tmp = (struct ListNode*)malloc(sizeof(struct ListNode));
        tmp->next = NULL;
        tmp->val = n;
        sum->next = tmp;
    }
    return ReverseList(head->next);
}

struct ListNode* ReverseList(struct ListNode* head) {
    struct ListNode* prev, *next;
    prev =  NULL;
    next = NULL;
    while (head) {
        next = head->next;
        head->next = prev;
        prev = head;
        head = next;
    }
    return prev;
}

全部评论

相关推荐

牛客868257804号:九个中铁八个中建
点赞 评论 收藏
分享
粗心的雪碧不放弃:纯学历问题,我这几个月也是一直优化自己的简历,后来发现优化到我自己都觉得牛逼的时候,发现面试数量也没有提升,真就纯学历问题
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务