void input();
该函数利用scanf
从输入中获取学生的信息,并将其组织成单向链表。链表节点结构定义如下:
struct stud_node {
int num; /*学号*/
char name[20]; /*姓名*/
int score; /*成绩*/
struct stud_node *next; /*指向下个结点的指针*/
};
单向链表的头尾指针保存在全局变量head
和tail
中。
输入为若干个学生的信息(学号、姓名、成绩),当输入学号为0时结束。
#include
#include
#include
struct stud_node {
int num;
char name[20];
int score;
struct stud_node *next;
};
struct stud_node *head, *tail;
void input();
int main()
{
struct stud_node *p;
head = tail = NULL;
input();
for ( p = head; p != NULL; p = p->next )
printf("%d %s %d\n", p->num, p->name, p->score);
return 0;
}
/* 你的代码将被嵌在这里 */
1 zhang 78
2 wang 80
3 li 75
4 zhao 85
0
1 zhang 78
2 wang 80
3 li 75
4 zhao 85
#include
#include
#include
struct stud_node {
int num;
char name[20];
int score;
struct stud_node *next;
};
struct stud_node *head, *tail;
void input();
int main()
{
struct stud_node *p;
head = tail = NULL;
input();
for ( p = head; p != NULL; p = p->next )
printf("%d %s %d\n", p->num, p->name, p->score);
return 0;
}
/* 你的代码将被嵌在这里 */
void input()
{
struct stud_node *head, *p, *q;
head = (struct stud_node*)malloc(sizeof(struct stud_node));
scanf("%d%s%d", &head->num, head->name, &head->score);
p=head;
while(1)
{
q=(struct stud_node*)malloc(sizeof(struct stud_node));
scanf("%d", &q->num);
if(q->num==0)
break;
scanf("%s%d", q->name, &q->score);
p->next=q;
p = q;
}
q->next = NULL;
return;
}
错误1: *head 是全局变量,在函数中重复定义会导致函数中的修改屏蔽了全局变量。
也就是说,在函数中对*head的修改不会应用于全局删掉
错误2:“q->next=NULL”错误,此时q中只有q->num==0,应该用p,此时p为上一个q
更改:p->next = NULL;
错误3:内存泄露 更改:free(q);
错误4:测试样例中n=0时错误
应该让head=NULL;即创建一个空链表
void input()
{
struct stud_node *p, *q;
head = (struct stud_node*)malloc(sizeof(struct stud_node));
scanf("%d%s%d", &head->num, head->name, &head->score);
if(head->num==0)
head = NULL;
else
{p=head;
while(1)
{
q=(struct stud_node*)malloc(sizeof(struct stud_node));
scanf("%d", &q->num);
if(q->num==0)
break;
scanf("%s%d", q->name, &q->score);
p->next=q;
p = q;
}
p->next = NULL;
free(q);
return;}
}