题解 | 牛牛的双链表求和

牛牛的双链表求和

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

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
正在热议
更多
# 春招至今,你的战绩如何? #
4887次浏览 47人参与
# 你的实习产出是真实的还是包装的? #
1093次浏览 27人参与
# 巨人网络春招 #
11145次浏览 221人参与
# 军工所铁饭碗 vs 互联网高薪资,你会选谁 #
6891次浏览 36人参与
# 简历第一个项目做什么 #
31245次浏览 312人参与
# 当下环境,你会继续卷互联网,还是看其他行业机会 #
186328次浏览 1114人参与
# 米连集团26产品管培生项目 #
4064次浏览 196人参与
# 面试紧张时你会有什么表现? #
30317次浏览 188人参与
# 简历中的项目经历要怎么写? #
309349次浏览 4149人参与
# 网易游戏笔试 #
6302次浏览 83人参与
# 职能管理面试记录 #
10676次浏览 59人参与
# 把自己当AI,现在最消耗你token的问题是什么? #
6843次浏览 154人参与
# 从哪些方向判断这个offer值不值得去? #
56694次浏览 357人参与
# 腾讯音乐求职进展汇总 #
160388次浏览 1105人参与
# 小红书求职进展汇总 #
226842次浏览 1356人参与
# AI时代,哪些岗位最容易被淘汰 #
62375次浏览 727人参与
# 你怎么看待AI面试 #
179242次浏览 1162人参与
# 正在春招的你,也参与了去年秋招吗? #
362478次浏览 2631人参与
# 你的房租占工资的比例是多少? #
92122次浏览 896人参与
# 机械求职避坑tips #
94395次浏览 567人参与
# 校招笔试 #
466042次浏览 2950人参与
# 面试官最爱问的 AI 问题是...... #
27078次浏览 834人参与
牛客网
牛客网在线编程
牛客网题解
牛客企业服务