题解 | 牛牛的双链表求和

牛牛的双链表求和

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

#define  _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
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 ListNode {
        int data;
        struct ListNode* next;
    };
    //创建头节点
    struct ListNode* head1 = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* head2 = (struct ListNode*)malloc(sizeof(struct ListNode));
    //创建遍历指针
    struct ListNode* p1 = head1;
    struct ListNode* p2 = head2;
    //创建遍历数组指针
    int* ptr1 = &a[0];
    int* ptr2 = &b[0];
    //数组变链表
    for (int i = 0; i < n; i++)
    {
        //创建新节点
        struct ListNode* newnode1 = (struct ListNode*)malloc(sizeof(struct ListNode));
        struct ListNode* newnode2 = (struct ListNode*)malloc(sizeof(struct ListNode));
        newnode1->next = NULL;
        newnode1->data = a[i];
        newnode2->next = NULL;
        newnode2->data = b[i];
        p1->next = newnode1;
        p2->next = newnode2;
        p1 = p1->next;
        p2 = p2->next;
    }
    //链表a对应加到链表b
    p1 = head1->next; p2 = head2->next;
    while (p1 != NULL)
    {
        p1->data = p1->data + p2->data;
        printf("%d ", p1->data);
        p1 = p1->next;
        p2 = p2->next;
    }
    //释放动态内存
    p1 = head1->next; p2 = head2->next;
    while (p1 != NULL)
    {
        struct ListNode* temp = p1;
        struct ListNode* temp2 = p2;
        p1 = p1->next;
        p2 = p2->next;
        free(temp); free(temp2);
    }
    free(a);
    free(b);
    return 0;
}

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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