题解 | 链表相加(二)

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

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务