题解 | #牛牛的双链表求和#链表拆分
牛牛的双链表求和
https://www.nowcoder.com/practice/efb8a1fe3d1f439691e326326f8f8c95
#include <stdio.h>
#include <stdlib.h>
//思路:由于两链表等长,先创建h=2*a的链表,然后等长拆分为h,h1;最后做加法。
typedef struct Node //结点
{
int data;
struct Node *next;
}node;
node* link(int m) //创建链表
{
node *h,*p,*q;
h = (node*)malloc(sizeof(node));
h->next = NULL;
q= h;
for(int i =0;i<m;i++)
{
p = (node*)malloc(sizeof(node));
scanf("%d",&(p->data));
p->next = q->next; //尾插法
q->next = p;
q = p;
}
return h;
}
void out(node* h) //链表输出
{
node *p = h->next;
for(;p!=NULL;p =p->next)
{
printf("%d ",p->data);
}
printf("\n");
}
node* add(node*h1,node*h2) //链表相加
{
node *p1=h1->next,*p2 = h2->next;
while(p1!=NULL)
{
p1->data = p1->data+p2->data;
p1=p1->next;
p2=p2->next;
}
return h1;
}
int main() {
int a;
node *h,*h1,*h2,*p;
scanf("%d",&a);
h = link(2*a); //先创建h=2*a的链表
h1 = (node*)malloc(sizeof(node)); //后半段链表的头节点
h1->next = NULL;
p = h;
for(int i=0;i<a;i++) //找到前半段的尾节点
{
p =p->next;
}
// printf("\n %d\n",p->data); //可测试找到的尾节点是否正确
h1->next = p->next; //将h拆分,h1指向后半段的头,
p->next = NULL; //将前半段尾指空,
// out(h);
// out(h1); //可测试拆分是否正确
h2 = add(h,h1);
out(h2);
return 0;
}
