题解 | #牛牛的双链表求和#
牛牛的双链表求和
http://www.nowcoder.com/practice/efb8a1fe3d1f439691e326326f8f8c95
#include<stdio.h>
#include<stdlib.h>
int N;
int val1,val2;
struct ListNode
{
int data;
struct list_node *next;
};
typedef struct ListNode gut;
gut *creat_list_node(int c_data)//创建结点
{
gut *New_Node=NULL;
New_Node=(gut*)malloc(sizeof(gut));
memset(New_Node,0,sizeof(gut));
New_Node->data=c_data;
New_Node->next=NULL;
return New_Node;
}
gut *tail_node(gut *HeadNode,int t_data)//尾插
{
gut *new_node=creat_list_node(t_data);
gut *insert_node=HeadNode;
while(insert_node->next!=NULL)
{
insert_node=insert_node->next;
}
insert_node->next=new_node;
return insert_node;
}
gut *add_node(gut *HeadNode_1,gut *HeadNode_2)//加和
{
gut *add_1=HeadNode_1->next;//头结点是0,去除头结点
gut *add_2=HeadNode_2->next;
while(add_1 !=NULL)//遍历至尾结点
{
add_1->data=add_1->data+add_2->data;//加和
add_1=add_1->next;//下一结点
add_2=add_2->next;
}
return add_1;//返回加和后的链表
}
gut *print_node(gut *HeadNode)
{
gut *pri_node=HeadNode->next;
while(pri_node!=NULL)
{
printf("%d ",pri_node->data); //打印
pri_node=pri_node->next;//下一结点
}
printf("\n");
return pri_node->data;//不要忘了返回值
}
int main()
{
gut *HeadNode1=creat_list_node(N);//创建两个头结点(相当于开辟两个存储空间)
gut *HeadNode2=creat_list_node(N);
while(scanf("%d\n",&N)!=EOF)
{
for(int i=0;i<N;i++)//链表a
{
scanf("%d ",&val1);
tail_node(HeadNode1, val1);
}
for(int i=0;i<N;i++)//链表b
{
scanf("%d ",&val2);
tail_node(HeadNode2, val2);
}
add_node(HeadNode1,HeadNode2) ;//加和
print_node(HeadNode1);//打印
}
free(HeadNode1);//释放内存
free(HeadNode2);
return 0;
}