本题要求实现一个将输入的学生成绩组织成单向链表的简单函数。
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
void input()
{
int num;
struct stud_node *p,*pre,*s;
scanf("%d",&num);
while(num!=0)
{
s=head->next;
while(s!=NULL)
{
pre=s;
s=s->next;
}
p=(struct stud_node *)malloc(sizeof(struct stud_node));
p->num=num;
scanf("%s%d",p->name,&p->score);
p->next=pre->next;
pre->next=p;
scanf("%d",&num);
}
}
基于Monster 组和GPT的调写:
void input()
{
int num;
struct stud_node* p;
scanf("%d", &num);
while (num != 0) {
p = (struct stud_node*)malloc(sizeof(struct stud_node));
p->num = num;
scanf("%s %d", p->name, &p->score);
p->next = NULL;
if (head == NULL) {
head = tail = p;
} else {
tail->next = p;
tail = p;
}
scanf("%d", &num);
}
}
供参考:
#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);
system("pause");
return 0;
}
/* 你的代码将被嵌在这里 */
void input()
{
int num;
struct stud_node *p;
while (1)
{
scanf("%d", &num);
if (num == 0) break;
p = (struct stud_node *)malloc(sizeof(struct stud_node));
p->next = NULL;
p->num = num;
scanf("%s %d", p->name, &p->score);
if (!head)
head = p;
else
tail->next = p;
tail = p;
}
}
题目要求:
有 2 个学生信息,放在结构体数组中,要求输出学生信息
#include <stdio.h>
struct Student //声明结构体类型struct Student
{
int num;
char name[20];
float score;
};
// 定义结构体数组并初始化
struct Student stu[2]={{1,"Anna",95.0},{2,"Snowy",98.5}};
int main()
{
// 定义指向struct Student 结构体变量的指针变量
struct Student *p;
printf(" N0. Name Score\n");
for(p=stu;p<stu+2;p++)
{
printf(" %-4d %-10s%.1f\n",p->num,p->name,p->score);
}
return 0;
}