题解 | #牛牛的双链表求和#
牛牛的双链表求和
https://www.nowcoder.com/practice/efb8a1fe3d1f439691e326326f8f8c95
#include <stdio.h> #include <stdlib.h> typedef struct node{ int data; struct node *next; }node; node *createlist() { node *head = malloc(sizeof(node)); if(head == NULL){ printf("out of memory"); exit(1); } head->next = NULL; return head; } void add_node(node *head, int n,int *q) { //用尾插法实现 node *p = head; for (int i =0; i < n; i++) { node *newnode = malloc(sizeof(node));//每循环一次都要创建一块内存空间,链表的内存空间不需要连续 if (newnode == NULL) { printf("out of memory"); exit(1); } newnode->data = q[i]; //但是所储存的数据一定是按数组元素的顺序连接起来的 p->next = newnode; //p的指针域指向新节点 p = newnode; //p指针向后移动指向当前最后一个节点 } //全部添加完成,把最后一个节点的指针域置为空 p->next = NULL; } node *sum_node(node *head1,node *head2) { node *p = head1->next; node *q = head2->next; while(p != NULL) { q->data = (q->data) + (p->data); p = p->next; q = q->next; } return head2; } int main() { int n; scanf("%d", &n); int arr1[n]; int arr2[n]; node *head1 = createlist(); //创建带头节点的空链表 node *head2 = createlist(); for (int i = 0; i < n; i++) { scanf("%d", &arr1[i]); //填充数组元素 } add_node(head1,n, &arr1[0]); //建立单链表head1,传入数组元素个数和数组起始位置,和链表指针 for (int j = 0; j < n; j++) { scanf("%d", &arr2[j]); } add_node(head2,n, &arr2[0]); node *head3 = sum_node(head1,head2); //两个链表合并,返回头指针 node *p = head3->next; //声明指针p指向链表第一个带数值的节点 while(p != NULL) { printf("%d ", p->data); p = p->next; } printf("\n"); return 0; }