题解 | 牛牛的双链表求和

牛牛的双链表求和

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

#include <stdio.h>
#include <stdlib.h>

// write your code here......
struct node
{
    int data;
    struct node* next;
};

struct node* list1(int arr[],int n)
{
    struct node* list1= (struct node*)malloc(sizeof(struct node));
    if(list1==NULL)
    {
        return NULL;
    }
    struct node* p1=list1;
    for(int i=0;i<n;i++)
    {
        struct node* tem1=(struct node*)malloc(sizeof(struct node));
        tem1->data=arr[i];
        p1->next=tem1;
        p1=p1->next;
    }
    p1->next=NULL;
    return list1;
}

struct node* list2(int arr[],int n)
{
    struct node* list2= (struct node*)malloc(sizeof(struct node));
    if(list2==NULL)
    {
        return NULL;
    }
    struct node* p2=list2;
    for(int i=0;i<n;i++)
    {
        struct node* tem2=(struct node*)malloc(sizeof(struct node));
        tem2->data=arr[i];
        p2->next=tem2;
        p2=p2->next;
    }
    p2->next=NULL;
    return list2;
}


int main() {

    int n;
    scanf("%d",&n);

    int* a=(int*)malloc(n*sizeof(int));

    for (int i = 0; i < n; i++) {
        scanf("%d",&a[i]);
    }

    int* b=(int*)malloc(n*sizeof(int));

    for (int i = 0; i < n; i++) {
        scanf("%d",&b[i]);
    }

    // write your code here......
    struct node* a1=list1(a,n);
    struct node* a2=list2(b,n);

    struct node* p1=a1->next;
    struct node* p2=a2->next;

    while(p1 !=NULL && p2 !=NULL)
    {
        p2->data=p1->data+p2->data;
        p1=p1->next;
        p2=p2->next;
    }
    
    p2=a2->next;

    while(p2 != NULL)
    {
        printf("%d ",p2->data);
        p2=p2->next;
    }

    free(a);
    free(b);
    return 0;
}

全部评论

相关推荐

09-14 20:51
四川大学 Java
慢热的鲸鱼在学习:985加粗就行了,第二个项目来不及准备也没事,省的写了问你你还不会。你只需准备面试八股和项目场景,剩下的交给985。即使面不过也没事,面试经验是最重要的,你现在不缺时间
简历中的项目经历要怎么写
点赞 评论 收藏
分享
09-12 11:55
已编辑
湖南工商大学 Java
那一天的Java_J...:这种一堆问题的,别去
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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