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

链表相加(二)

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

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 * };
 */
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param head1 ListNode类 
 * @param head2 ListNode类 
 * @return ListNode类
 */
struct ListNode* addInList(struct ListNode* head1, struct ListNode* head2 ) {
    // write code here
    if(head1->val == 0) return head2;
    if(head2->val == 0) return head1;
    struct ListNode* H1last = (struct ListNode*)malloc(sizeof(struct ListNode));
    H1last->val = -1;
    H1last->next = head1;
    struct ListNode* c1 = head1->next;
    struct ListNode* t;
    while(c1){
        t = c1;
        c1 = c1->next;
        head1->next = t->next;
        t->next = H1last->next;
        H1last->next = t;
    }
    c1 = H1last->next;
    struct ListNode* H2last = (struct ListNode*)malloc(sizeof(struct ListNode));
    H2last->val = -1;
    H2last->next = head2;
    struct ListNode* c2 = head2->next;
    while(c2){
        t = c2;
        c2 = c2->next;
        head2->next = t->next;
        t->next = H2last->next;
        H2last->next = t;
    }
    c2 = H2last->next;
    int sum = 0;
    int i = 0;
    struct ListNode* H = NULL;
    while(c1 && c2){
        sum = c1->val + c2->val;
        if(i == 1) sum++;
        struct ListNode* pt = (struct ListNode*)malloc(sizeof(struct ListNode));
            pt->val = sum%10;
            pt->next = NULL;
            //printf("pt=%d\n",pt->val);
            
            if(sum>9) i=1;
            else i=0;
            if(H==NULL){
                H = pt; 
            } 
            else{
                pt->next = H;
                H = pt;
            }     
        c1 = c1->next;
        c2 = c2->next;   
    }
    if(c1 == NULL && c2 == NULL)
    return H;
    struct ListNode* tt = c1 == NULL? c2:c1;
    while(tt->next){
        t = tt;
        tt = tt->next;
        if(i == 1){
            t->val++;
            if(t->val == 10){
                t->val = 0;
            }
            else i = 0;
        }
        t->next = H;
        H = t;
    }
    if(i == 1){
        tt->val++;
        if(tt->val == 10){
            struct ListNode* new = (struct ListNode*)malloc(sizeof(struct ListNode));
            new->val = 0;
            new->next = H;
            H = new;
            tt->val = 1;
        }
    }
    tt->next = H;
    H = tt;
    return H;
}

全部评论

相关推荐

一个菜鸡罢了:哥们,感觉你的简历还是有点问题的,我提几点建议,看看能不能提供一点帮助 1. ”新余学院“别加粗,课程不清楚是否有必要写,感觉版面不如拿来写一下做过的事情,教育经历是你的弱势就尽量少写 2. “干部及社团经历”和“自我评价”删掉 3. 论文后面的“录用”和“小修”啥的都删掉,默认全录用,问了再说,反正小修毕业前肯定能发出来 4. 工作经验和研究成果没有体现你的个人贡献,着重包装一下个人贡献
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务