本题要求实现两个函数,一个将输入的学生成绩组织成单向链表;另一个将成绩低于某分数线的学生结点从链表中删除。
函数接口定义:
struct stud_node *createlist();
struct stud_node *deletelist( struct stud_node *head, int min_score );
函数createlist利用scanf从输入中获取学生的信息,将其组织成单向链表,并返回链表头指针。链表节点结构定义如下:
struct stud_node {
int num; /学号/
char name[20]; /姓名/
int score; /成绩/
struct stud_node *next; /指向下个结点的指针/
};
输入为若干个学生的信息(学号、姓名、成绩),当输入学号为0时结束。
函数deletelist从以head为头指针的链表中删除成绩低于min_score的学生,并返回结果链表的头指针。
裁判测试程序样例:
#include <stdio.h>
#include <stdlib.h>
struct stud_node {
int num;
char name[20];
int score;
struct stud_node *next;
};
struct stud_node *createlist();
struct stud_node *deletelist( struct stud_node *head, int min_score );
int main()
{
int min_score;
struct stud_node *p, *head = NULL;
head = createlist();
scanf("%d", &min_score);
head = deletelist(head, min_score);
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
80
输出样例:
2 wang 80
4 zhao 85
struct stud_node *createlist()
{
struct stud_node *current,*prev,*head;
head=NULL;
current=(struct stud_node*)malloc(sizeof (struct stud_node));
scanf("%d",¤t->num);
while(current->num){
scanf("%s %d",current->name,¤t->score);
current->next=NULL;
if(head==NULL){
head=current;
}else{
prev->next=current;
}prev=current;
current=(struct stud_node*)malloc(sizeof(struct stud_node));
scanf("%d",¤t->num);
}return head;
}
struct stud_node *deletelist( struct stud_node *head, int min_score )
{
struct stud_node *tail,*body;
while(head!=NULL&&head->score<min_score){
body=head;
head=head->next;//先处理链表从头就需要删除的情况
free(body);//释放内存空间
}
if(head==NULL)//如果删空了则直接返回NULL
return NULL;
//处理正常情况,head中成绩大于min_score
body=head;
tail=body->next;
while(tail!=NULL){
if(tail->score<min_score){
body->next=tail->next;//重新连接
free(tail);//释放内存
}else body=tail;
tail=body->next;
}return head;
}
做链表操作时可在脑海中自行想象出首尾相连的一条链,联想写代码会更加容易。若还是不理解可拿纸跟着流程走一遍。
2020/2/4——By Suki