题解 | #牛牛的双链表求和#
牛牛的双链表求和
https://www.nowcoder.com/practice/efb8a1fe3d1f439691e326326f8f8c95
#include <stdio.h>
#include <stdlib.h>
typedef struct linklist
{
int data;
struct linklist *next;
}linklist;
//创建链表节点
linklist *create_node(int x)
{
linklist *pnew = (linklist*)malloc(sizeof(linklist));
pnew->data = x;
pnew->next = NULL;
return pnew;
}
linklist *insert_linklistlist(linklist *head,int data)
{
linklist *p = head ;
linklist *newnode = create_node(data);
if( head -> next == NULL)
{
head -> next = newnode;
}
else
{
while ( p -> next != NULL)
{
p = p -> next;
}
p -> next = newnode;
}
return head;
}
void print_linklist(linklist *head)
{
linklist *p = head->next;
while (p != NULL)
{
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
linklist *add_linklist_all(linklist *head,linklist *Bhead)
{
linklist *p = head->next;
linklist *pre = Bhead->next;
while(p!= NULL)
{
pre->data += p->data;
p = p->next;
pre = pre->next;
}
return Bhead;
}
int main()
{
int n = 0 ;
scanf("%d",&n);
int arry[n] ;
//创建带头节点的链表头节点
linklist *head = (linklist*)malloc(sizeof(linklist));
head->next = NULL;
head -> data = 10000;
linklist *Bhead = (linklist*)malloc(sizeof(linklist));
Bhead->next = NULL;
Bhead -> data = 10000;
//输入数组,插入节点
for(int i = 0 ; i < n ; i++)
{
scanf("%d",&arry[i]);
head = insert_linklistlist(head,arry[i]);
}
for(int i = 0 ; i < n ; i++)
{
scanf("%d",&arry[i]);
Bhead = insert_linklistlist(Bhead,arry[i]);
}
add_linklist_all(head, Bhead);
print_linklist(Bhead);
}

查看1道真题和解析