建立链表,统计链表中所有结点的数据域N之和
/*
典型例题:建立链表,统计链表中所有结点的数据域N之和
*/
#include<stdio.h>
#include<malloc.h>
struct node{
int n;
struct node *next;
};
struct node *create() //建立链表
{
struct node *head,*p1,*p2;
head=NULL;
p1=p2=(struct node *)malloc(sizeof(struct node )) ; //分配内存空间使p1和p2同时指向这个空间的起始地址
scanf("%d",&p1->n); //
while(p1->n!=0) //
{
if(head=NULL) //
head=p1;
else
p2->next=p1;
p2=p1;
p1=(struct node *)malloc(sizeof(struct node));
scanf("%d",&p1->n);
}
p2->next=NULL;
return head; //返回链表的头指针
}
int add(struct node *head) //把结点加入链表中
{
struct node *p;
int sum=0; //定义sum变量存放数据域n的和
p=head;
while(p!=NULL)
{
sum+=p->n;
p=p->next;
}
return sum; //向主调函数返回sum的值,即数据域n的和
}
void main()
{
struct node *head;
int m;
head=create();
m=add(head);
printf("%d\n",m);
}
输入值始终得到sum的值为0,哪点错了?????????????
[解决办法]
不适当的条件判断导致了你的状况,改成下面这样就好了:
- C/C++ code
struct node *create() //建立链表{ struct node *head,*p1,*p2; //head=NULL; head=p1=p2=(struct node *)malloc(sizeof(struct node )) ; //分配内存空间使p1和p2同时指向这个空间的起始地址 scanf("%d",&p1->n); // while(p1->n!=0) // { p2->next=p1; p2=p1; p1=(struct node *)malloc(sizeof(struct node)); scanf("%d",&p1->n); } p2->next=NULL; return head; //返回链表的头指针 }
[解决办法]
问题1:
if(head=NULL)
head=p1;
改为:
if(head==NULL)
head=p1;
问题2:你的p2貌似什么用都没有.create函数最多将p1赋值给head,p1的最后一次输入是0,则head->n=0,且只有这一个节点.