题解 | #牛牛的双链表求和#
牛牛的双链表求和
https://www.nowcoder.com/practice/efb8a1fe3d1f439691e326326f8f8c95
#include <stdio.h>
typedef struct node{
int data;
struct node *next;
}node;
int sum_node(node *head);
void printf_node(node *head);
void add_node(node *head,int data);
node* sum_double_node(node* head_1,node* head_2);
node *cteat_node();
int main() {
int n,e,count;
node *head_1=cteat_node();
node *head_2=cteat_node();
scanf("%d ",&n);
count =0;
while (scanf("%d ", &e) != EOF) {
count++;
add_node(head_1,e);
if(count == n)break;
}
count =0;
while (scanf("%d ", &e) != EOF) {
add_node(head_2,e);
}
node *head_3=sum_double_node(head_1,head_2);
printf_node(head_3);
//printf_node(head_1);
return 0;
}
//创建头链表
//返回值为链表表头
//链表头默认data=0;
//链表尾->next = NULL
node *cteat_node(){
node *head=(node *)malloc(sizeof(node));
head->next=NULL;
return head;
}
//尾插添加
// head为链表头 data为数据
void add_node(node *head,int data){
node *pT=NULL;
node *new=(node *)malloc(sizeof(node));
new->data=data;
for(pT=head;pT->next!=NULL;pT=pT->next){};//表尾->next为NULL
pT->next=new;//链接
}
//打印链表
//head为表头
void printf_node(node *head){
for(node *pT=head;pT!=NULL;pT=pT->next){
if(pT!=head)printf("%d ",pT->data);
}
}
//函数功能:求和
//函数参数:head 表头
//函数返回值:int sum
int sum_node(node *head){
int sum=0;//求和值sum
for(node *pT= head;pT != NULL; pT= pT->next ){
sum+=pT->data;
}//循环到pT=NULL sum累加
return sum;
}
//function : 链表2连接到链表1后
//parame : 链表1表头head_1 链表2表头 head_2
node* sum_double_node(node* head_1,node* head_2){
node *head_3=cteat_node();
int count1=0;
int count2=0;
for(node *pT_1= head_1; pT_1 != NULL;pT_1=pT_1->next){
count2=0;
count1++;
for(node *pT_2= head_2; pT_2 != NULL;pT_2=pT_2->next) {count2++;
if(count1 == count2 && count1 !=1) add_node(head_3,pT_1->data+pT_2->data);
}
}
return head_3;
}
字节跳动公司福利 1297人发布