题解 | 牛牛的双链表求和
牛牛的双链表求和
https://www.nowcoder.com/practice/efb8a1fe3d1f439691e326326f8f8c95
#include <stdio.h>
#include <stdlib.h>
// write your code here......
struct node
{
int data;
struct node* next;
};
struct node* list1(int arr[],int n)
{
struct node* list1= (struct node*)malloc(sizeof(struct node));
if(list1==NULL)
{
return NULL;
}
struct node* p1=list1;
for(int i=0;i<n;i++)
{
struct node* tem1=(struct node*)malloc(sizeof(struct node));
tem1->data=arr[i];
p1->next=tem1;
p1=p1->next;
}
p1->next=NULL;
return list1;
}
struct node* list2(int arr[],int n)
{
struct node* list2= (struct node*)malloc(sizeof(struct node));
if(list2==NULL)
{
return NULL;
}
struct node* p2=list2;
for(int i=0;i<n;i++)
{
struct node* tem2=(struct node*)malloc(sizeof(struct node));
tem2->data=arr[i];
p2->next=tem2;
p2=p2->next;
}
p2->next=NULL;
return list2;
}
int main() {
int n;
scanf("%d",&n);
int* a=(int*)malloc(n*sizeof(int));
for (int i = 0; i < n; i++) {
scanf("%d",&a[i]);
}
int* b=(int*)malloc(n*sizeof(int));
for (int i = 0; i < n; i++) {
scanf("%d",&b[i]);
}
// write your code here......
struct node* a1=list1(a,n);
struct node* a2=list2(b,n);
struct node* p1=a1->next;
struct node* p2=a2->next;
while(p1 !=NULL && p2 !=NULL)
{
p2->data=p1->data+p2->data;
p1=p1->next;
p2=p2->next;
}
p2=a2->next;
while(p2 != NULL)
{
printf("%d ",p2->data);
p2=p2->next;
}
free(a);
free(b);
return 0;
}

查看13道真题和解析