题解 | 链表相加(二)

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 * };
 */
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param head1 ListNode类 
 * @param head2 ListNode类 
 * @return ListNode类
 */
#include <stdlib.h>
struct ListNode* addInList(struct ListNode* head1, struct ListNode* head2 ) {
    // write code here
    if(head1==NULL&&head2==NULL)
        return NULL;
    struct ListNode* newhead1=NULL;
    struct ListNode* newhead2=NULL;
    struct ListNode* cur;
    struct ListNode* next=NULL;
    //反转head1,newhead1为新链表的头节点
    cur=head1;
    while(cur!=NULL)
    { 
        next=cur->next;
        cur->next=newhead1;
        newhead1=cur;
        cur=next;
    }
     //反转head2,newhead2为新链表的头节点
    cur=head2;
    while(cur!=NULL)
    { 
        next=cur->next;
        cur->next=newhead2;
        newhead2=cur;
        cur=next;
    }
    //把两个链表的val加起来,两个val的和存回两个val
    cur=newhead1;
    next=newhead2;
    while(newhead1&&newhead2)
    {
        newhead1->val=newhead2->val=newhead1->val+newhead2->val;
        newhead1=newhead1->next;
        newhead2=newhead2->next;
    }
    //newhead1,newhead2重新指向长的那条链表的头节点
    if(newhead2)
        newhead1=newhead2=next;
    else
        newhead1=newhead2=cur;
    //遍历链表,有val大于10的节点,这个节点的val减10,下一节点的val加一,newhead1指向长链表的头
    while(newhead2->next)
    {
        if(newhead2->val>9)
        {
            newhead2->val=newhead2->val-10;
            newhead2->next->val++;  
        }        
        newhead2=newhead2->next;
    }
    //如果最后一个节点大于10
    if(newhead2->val==10)
    {
        newhead2->next=malloc(sizeof(struct ListNode));
        newhead2->val=newhead2->val-10;
        newhead2->next->val=1;
        newhead2->next->next=NULL;
    }
    //反转长链表
    cur=newhead1;
    //newhead1置为null,准备指向反转后的长链表的头节点
    newhead1=NULL;
    while(cur!=NULL)
    { 
        next=cur->next;
        cur->next=newhead1;
        newhead1=cur;
        cur=next;
    }
    return newhead1;
}

全部评论

相关推荐

06-15 02:05
已编辑
南昌航空大学 数据分析师
Eason三木:你如果想干技术岗,那几个发公众号合唱比赛的经历就去掉,优秀团员去掉,求职没用。然后CET4这种不是奖项,是技能,放到下面的专业技能里或者单独列一个英语能力。 另外好好改改你的排版,首行缩进完全没有必要,行间距好好调调,别让字和标题背景黏在一起,你下面说能做高质量PPT你得展现出来啊,你这简历排版我用PPT做的都能比你做的好。 然后自我评价,你如果要干数据工程师,抗压能力强最起码得有吧。
简历中的项目经历要怎么写
点赞 评论 收藏
分享
06-27 18:45
中山大学 Ruby
25届应届毕业生,来广州2个礼拜了,找不到工作,绝望了,太难过了…
应届想染班味:9爷找不到工作只能说明,太摆了或者太挑了。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务