题解 | #牛牛的单链表求和#
牛牛的单链表求和
https://www.nowcoder.com/practice/a674715b6b3845aca0d5009bc27380b5
#include <stdio.h>
/*int main() {
int a, b;
while (scanf("%d %d", &a, &b) != EOF) { // 注意 while 处理多个 case
// 64 位输出请用 printf("%lld") to
printf("%d\n", a + b);
}
return 0;
}*/
#include <malloc.h>
typedef struct node
{
int data;
struct node *next;
}node;
//创建头结点
node *creatnode()
{
node *p=(node*)malloc(sizeof(node));
if(p==NULL)
{
return NULL;
}
//p->data=data;
p->next=NULL;
return p;
}
//尾插
void insertnode(node *p,int data)
{
node *new=(node*)malloc(sizeof(node));
if(p==NULL)
return;
while(p->next!=NULL)
{
p=p->next;
}
new->data=data;
new->next=p->next;
p->next=new;
}
//打印
void printfnode(node *p)
{
int sum;
while(p->next!=NULL)
{
sum+=p->data;
p=p->next;
}
sum=sum+p->data;
printf("%d",sum);
}
int main()
{
int n;
scanf("%d",&n);
int a[n],j,i;
// scanf("%d",&a[0]);
for(j=0;j<n;j++)
{
scanf("%d",&a[j]);
}
node *head=creatnode();
for(i=0;i<n;i++)
{
insertnode(head, a[i]);
}
//swapnode(head);
printfnode(head);
return 0;
}