题解 | #牛牛的双链表求和#

牛牛的双链表求和

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

#include <stdio.h>


typedef struct NODE {
    int data;
    struct NODE* next;
} node;
typedef struct Link {
    node* head;
} link;
void createlinke(node* head, int a[], int n) {
    node* p, *s;
    p = (node*)malloc(sizeof(node));
    p->data = a[0];
    head->next = p;
    s = p;
    for (int i = 1; i < n; i++) {
        p = (node*)malloc(sizeof(node));
        p->data = a[i];
        s->next = p;
        s = p;
    }
    s->next = NULL;
}
void freeLinkedList(node* head) {
    node* temp;
    while (head != NULL) {
        temp = head;
        head = head->next;
        free(temp);
    }
}
int main() {
    int n;
    scanf("%d", &n);
    int a[n], b[n];
    for (int i = 0; i < n; i++)
        scanf("%d", &a[i]);
    for (int i = 0; i < n; i++)
        scanf("%d", &b[i]);
    link* p2;
    link* p1;
    p1 = (link*)malloc(sizeof(link));
    p1->head = (node*)malloc(sizeof(node));
    p1->head->next = NULL;
    p2 = (link*)malloc(sizeof(link));
    p2->head = (node*)malloc(sizeof(node));
    p2->head->next = NULL;
    createlinke(p1->head, a, n);
    createlinke(p2->head, b, n);

    node* pre1, *pre2;
    pre1 = p1->head->next;
    pre2 = p2->head->next;
    while (pre1 != NULL) {

        pre1->data += pre2->data;
        pre1 = pre1->next;
        pre2 = pre2->next;
    }
    pre1 = p1->head->next;
    while (pre1 != NULL) {
        printf("%d ", pre1->data);
        pre1 = pre1->next;
    }

    freeLinkedList(p1->head);
    freeLinkedList(p2->head);




}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务