题解 | #牛牛的双链表求和#
牛牛的双链表求和
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;
}

