建立学生信息链表

qq_38666150 2017-05-06 12:29:41
题目:
本题要求实现一个将输入的学生成绩组织成单向链表的简单函数。

函数接口定义:

void input();
该函数利用scanf从输入中获取学生的信息,并将其组织成单向链表。链表节点结构定义如下:

struct stud_node {
int num; /*学号*/
char name[20]; /*姓名*/
int score; /*成绩*/
struct stud_node *next; /*指向下个结点的指针*/
};
单向链表的头尾指针保存在全局变量head和tail中。

输入为若干个学生的信息(学号、姓名、成绩),当输入学号为0时结束。

裁判测试程序样例:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

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

答案:(测试正确,但是用pta交上去之后有一个测试点是错误的)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct stud_node
{
int num;
char name[20];
int score;
struct stud_node *next;
}*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 *q;
int score;
char name[20];
q=(struct stud_node *)malloc(sizeof(struct stud_node));
scanf("%d",&q->num);
while(q->num!=0)
{
scanf("%s %d",name,&score);
strcpy(q->name,name);
q->score=score;
q->next=NULL;
if(head==NULL)
{
head=q;
tail=q;
}
else
{
tail->next=q;
}
tail=q;
q=(struct stud_node *)malloc(sizeof(struct stud_node));
scanf("%d",&q->num);
}
tail->next=NULL;
}
...全文
1377 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
fariy__ 2020-03-18
  • 打赏
  • 举报
回复
void input()
{
struct stud_node *q;
int score;
char name[20];
q=(struct stud_node *)malloc(sizeof(struct stud_node));
scanf("%d",&q->num);
if(q->num==0) head=NULL;
else
{
while(q->num!=0)
{
scanf("%s %d",name,&score);
strcpy(q->name,name);
q->score=score;
q->next=NULL;
if(head==NULL)
{
head=q;
tail=q;
}
else tail->next=q;
tail=q;
q=(struct stud_node *)malloc(sizeof(struct stud_node));
scanf("%d",&q->num);
}
tail->next=NULL;
}
}

考虑输入的第一个数就是0 ,程序会崩的情况

13,825

社区成员

发帖
与我相关
我的任务
社区描述
C++ Builder相关内容讨论区
社区管理员
  • 基础类社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧