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

链表相加(二)

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;
}

全部评论

相关推荐

无敌虾孝子:喜欢爸爸还是喜欢妈妈
点赞 评论 收藏
分享
11-18 09:44
Java
小白也想要offer:简历别放洋屁,搞不还还放错了,当然你投外企除外,以上纯属个人观点
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务