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

牛牛的双链表求和

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

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

typedef struct ListNode {
    int element;
    struct ListNode* next;
} ListNode;

typedef struct List {
    int length;
    ListNode* head;
} List;

void ListInit(List* list) {
    list->length = 0;
    list->head = NULL;
}

void ListDestory(List* list) {
    while (list->head != NULL) {
        ListNode* temp = list->head;
        list->head = list->head->next;
        free(temp);
    }

}

void ListInsert(List* list, int pos, int data) {
    if (pos < 0 || pos > list->length)
        return ;
    ListNode* newNode = (ListNode*)malloc(sizeof(ListNode));
    newNode->element = data;
    if (pos == 0) {
        newNode->next = list->head;
        list->head = newNode;
    } else if (pos == list->length) {
        ListNode* Current = list->head;
        for (int i = 0; i < pos - 1; ++i) {
            Current = Current->next;
        }
        Current->next = newNode;
        newNode->next = NULL;
    } else {
        ListNode* Current = list->head;
        for (int i = 0; i < pos; ++i) {
            Current = Current->next;
        }
        newNode->next = Current->next;
        Current->next = newNode;
    }
    list->length++;
}

void ListAdd(List* list1, List* list2){
    if(list1->head == NULL || list2->head == NULL){
        return ;
    }
    ListNode* list1_flag = list1->head;
    ListNode* list2_flag = list2->head;
    int length = list1->length;
    for(int i = 0; i < length; ++i){
        list1_flag->element += list2_flag->element;
        list1_flag = list1_flag->next;
        list2_flag = list2_flag->next;
    }
}

void ListPrint(List* list) {
    for (int i = 0; i < list->length; ++i) {
        printf("%d ", list->head->element);
        list->head = list->head->next;
    }
}

int main() {
    int n;
    scanf("%d", &n);
    int arr1[n], arr2[n];
    for (int i = 0; i < n; ++i) {
        scanf("%d ", &arr1[i]);
    }
        for (int i = 0; i < n; ++i) {
        scanf("%d ", &arr2[i]);
    }
    List list1, list2;
    ListInit(&list1);
    ListInit(&list2);
    for (int j = 0; j < n; ++j) {
        ListInsert(&list1, j, arr1[j]);
    }
    for (int j = 0; j < n; ++j) {
        ListInsert(&list2, j, arr2[j]);
    }
    ListAdd(&list1, &list2);
    ListPrint(&list1);
    ListDestory(&list1);
    ListDestory(&list2);

    return 0;
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-07 13:35
虽然不怎么光彩,经过这件事,可能我真的要去认同“面试八股文早该淘汰!不会用AI作弊的程序员=新时代文盲!”这句话了
HellowordX:Ai的出现是解放劳动力的,不是用来破坏公平竞争环境的,这样下去,轻则取消所有线上面试,严重了会影响整个行业对所有人产生影响,企业会拉高入职考核各种离谱考核会层出不穷
你找工作的时候用AI吗?
点赞 评论 收藏
分享
06-13 10:15
门头沟学院 Java
想去夏威夷的大西瓜在...:我也是27届,但是我现在研一下了啥项目都没有呀咋办,哎,简历不知道咋写
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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