题解 | #牛牛的双链表求和#
牛牛的双链表求和
https://www.nowcoder.com/practice/efb8a1fe3d1f439691e326326f8f8c95
多写你就明白了 #include<stdio.h> #include<stdlib.h> typedef struct Doublelist{ int value; struct Doublelist*next; struct Doublelist*prev; }Doublelist; Doublelist*creatNode(int value) { Doublelist*newnode = (Doublelist*)malloc(sizeof(Doublelist)); newnode->value= value; newnode->next = NULL; return newnode; } Doublelist*creatlist(int*array,int n) { if(n==0) return NULL; Doublelist*head= creatNode(array[0]); Doublelist*current = head; for(int i = 1;i<n;i++) { current->next= creatNode(array[i]); current = current->next; } return head; } int*summry2(Doublelist*head1,Doublelist*head2,int n) { Doublelist*current1 = head1; Doublelist*current2 = head2; int sum; int*array3=(int*)malloc(n*sizeof(int)); int i = 0; while(current1!=NULL) { sum = (current1->value)+(current2->value); current1 = current1->next; current2 = current2->next; array3[i] = sum; i++; } return array3; } int main() { int n; scanf("%d",&n); int*array1= (int*)malloc(n*sizeof(int)); int*array2= (int*)malloc(n*sizeof(int)); for(int i = 0;i<n;i++) { scanf("%d",&array1[i]); } for(int i = 0;i<n;i++) { scanf("%d",&array2[i]); } Doublelist*head1 = creatlist(array1,n); Doublelist*head2= creatlist(array2,n); int*array3= summry2(head1,head2,n); for(int i = 0;i<n;i++) { printf("%d ",array3[i]); } while(head1!=NULL) { Doublelist*temp = head1; head1 = head1->next; free(temp); } while(head2!=NULL) { Doublelist*temp = head2; head2 = head2->next; free(temp); } free(array1); free(array2); return 0; }