题解 | #牛牛的单链表求和#
牛牛的单链表求和
http://www.nowcoder.com/practice/a674715b6b3845aca0d5009bc27380b5
#include <stdio.h>
#include <stdlib.h>
typedef struct list{
int data;
struct list *next;
}list,*linklist;
//求和函数
int get_Sum_List(list *head)
{
list *point=head;
int sum=0;
while(point != NULL)
{
sum += point->data;
point = point->next;
}
return sum;
}
#if 1
int main()
{
int i,n;
scanf("%d",&n);
int arr[n];
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
//链表的创建
list *headList = NULL;
list *arrList = NULL;
list *head = NULL;
head = headList; //防止 headList 不为空链表的时候,而导致下面循环链表无头
//尾插法
for(i=0;i<n;i++)
{
arrList = (list *)malloc(sizeof(list));
arrList->data = arr[i];
arrList->next = NULL; //将headList放在arrList->next,即arrList的数据是放在headList的前面的
//headList=head;
if(headList == NULL)
{
headList = arrList; //
head = headList;
}
else
{
while(headList->next != NULL)
{
headList = headList->next ;
}
headList->next = arrList;
}
}
//ptink(head);
printf("%d",get_Sum_List(head));
return 0;
}
#endif
#include <stdlib.h>
typedef struct list{
int data;
struct list *next;
}list,*linklist;
//求和函数
int get_Sum_List(list *head)
{
list *point=head;
int sum=0;
while(point != NULL)
{
sum += point->data;
point = point->next;
}
return sum;
}
#if 1
int main()
{
int i,n;
scanf("%d",&n);
int arr[n];
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
//链表的创建
list *headList = NULL;
list *arrList = NULL;
list *head = NULL;
head = headList; //防止 headList 不为空链表的时候,而导致下面循环链表无头
//尾插法
for(i=0;i<n;i++)
{
arrList = (list *)malloc(sizeof(list));
arrList->data = arr[i];
arrList->next = NULL; //将headList放在arrList->next,即arrList的数据是放在headList的前面的
//headList=head;
if(headList == NULL)
{
headList = arrList; //
head = headList;
}
else
{
while(headList->next != NULL)
{
headList = headList->next ;
}
headList->next = arrList;
}
}
//ptink(head);
printf("%d",get_Sum_List(head));
return 0;
}
#endif
