题解 | #牛牛的双链表求和#
牛牛的双链表求和
https://www.nowcoder.com/practice/efb8a1fe3d1f439691e326326f8f8c95
#include <stdio.h> #include <stdlib.h> typedef struct node { int num; struct node* next; } Node; Node* create_list(int num) { Node* head=(Node*)malloc(sizeof(Node)); head->num=num; head->next=NULL; return head; } void add_node(Node* head,int num) { Node* p=(Node*)malloc(sizeof(Node)); p->num=num; p->next=NULL; Node* q=head; while(q->next) q=q->next; q->next=p; } int main() { int n; scanf("%d", &n); int a; scanf("%d", &a); Node* heada = create_list(a); for (int i = 1; i < n; i++) { scanf("%d", &a); add_node(heada, a); } int b; scanf("%d", &b); Node* headb = create_list(b); for (int i = 1; i < n; i++) { scanf("%d", &b); add_node(headb, b); } Node* pa=heada,*pb=headb; for(int i=0;i<n;i++) { pb->num+=pa->num; pa=pa->next; pb=pb->next; } pb=headb; for(int i=0;i<n;i++) { printf("%d ",pb->num); pb=pb->next; } while(heada) { pa=heada,pb=headb; heada=heada->next; headb=headb->next; free(pa); free(pb); } return 0; }