以前建立链表的时候由于链表建立成功的判定条件设置的不合理,造成建立链表的时候会存入不必要的数据。下面结合具体的代码来给大家分享一下
代码如下:
<span style="color:#cc33cc">#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct student
{
char name[20];
int num;
int age;
int score;
}Stu;
typedef struct Node
{
Stu stu;
Node *next;
}Node;
Node *p,*q,*L;
Node *Input();
int main()
{
input();
return 0;
}
Node *Input()
{
int a=0;
count=0;
char str[20];
while(1)
{
p=(Node *)malloc(sizeof(Node));
count++;
printf("请输入学生的信息:姓名 学号 年龄 分数\n");
scanf("%s",str);
if(count==1)
{
L=p;
q=p;
}
if(strcmp(str,"#")==0)
{
return L;
}
strcpy(p->stu.name,str);
scanf(" %d %d %d",&p->stu.num,&p->stu.age,&p->stu.score);
q->next = p;
q=p;
p->next=NULL;
}
}</span>
在这个程序里,有一个要点,和大家分享一下哦,就是在建立链表的过程中,如果建立结点分配空间的的语句在循环体内,应该保证,结点的后面指向空,即 p=(Node *)malloc(sizeof(Node));之后,一定要有一句 p->next=NULL;,为什么要这样呢,因为如果没有这句代码的话,链表的最后一个结点不指向空,就会造成地址访问冲突而报错。,这一点初学者很容易忽略。
当然了,还有另一种方法可以实现,这种方法就是设置一个判定条件,满足条件的话执行一次,链表添加结点和数据的函数,如此反复实现不断添加链表结点和数据的目的。具体实现代码如下:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct student
{
char name[20];
int num;
int age;
int score;
}Stu;
typedef struct Node
{
Stu stu;
Node *next;
}Node;
Node *p,*L,*q;
char str[10];
Node *Input();
void Print(Node *L);
int main()
{
p=L=q=(Node *)malloc(sizeof(Node));
L->next=NULL;
printf("是否要往链表中添加数据:输入YES 或者 NO\n");
scanf("%s",str);
while(strcmp(str,"YES")==0)
{
Input();
}
Print(L);
return 0;
}
Node *Input()
{
p=(Node *)malloc(sizeof(Node));
p->next=NULL;
printf("请输入学生的学号,姓名,年龄,成绩:\n");
scanf("%d %s %d %d",&p->stu.num,p->stu.name,&p->stu.age,&p->stu.score);
q->next=p;
q=p;
printf("是否要往链表中添加数据:输入YES 或者 NO\n");
scanf("%s",str);
return L;
}
void Print(Node *L)
{
p=L->next;
while(p!=NULL)
{
printf("%d %s %d %d",p->stu.num,p->stu.name,p->stu.age,p->stu.score);
p=p->next;
}
}
大家可以体会一下,两种建立链表的区别,有什么意见和建议可以随时交流哦。