提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
题目:
本题要求实现两个函数,一个将输入的学生成绩组织成单向链表;另一个将成绩低于某分数线的学生结点从链表中删除。
函数接口定义:
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
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
代码实现:
struct stud_node *createlist()
{//为了方便我创建了一个头结点L,题目要求返回头指针,所以最后返回L的下一位
struct stud_node *L=(struct stud_node *)malloc(sizeof(struct stud_node));
L->next=NULL;//创建头结点L
struct stud_node *tail=L;//根据输出数据得知用尾插法,设立尾指针tail,开始指向头结点L
int n;
scanf("%d",&n);//读入学号
while(n!=0){
struct stud_node *p=(struct stud_node *)malloc(sizeof(struct stud_node ));
p->next=NULL;
p->num=n;
scanf("%s",p->name);
scanf("%d",&p->score);建立新结点p,读入一行的数据赋给p
tail->next=p;//尾结点的下一位指向p
tail=p;//尾指针指向p(插入p后p成为尾结点啦)
scanf("%d",&n);//不要忘记读入学号噢
}
struct stud_node *q=L->next;//q指向头结点L的下一位也就是头指针
return q;//返回头指针
}
struct stud_node *deletelist( struct stud_node *head, int min_score )
{//这里传进来的head没有头结点,为了方便设立头结点q
struct stud_node *p=head,*q,*h;
q=(struct stud_node *)malloc(sizeof(struct stud_node));
q->next=head,h=q;//h指向q,因为q和p在下面的代码中移动了位置,而最后要返回删除后的头指针的位置
while(p){//p不为空时
if(p->score>=min_score){//不低于,p往后移动
q=p;//q指向p的前一位,令q先指向p
p=p->next;//p后移一位,注意这两句顺序不能反噢
}
else{//低于,删除P结点
q->next=p->next;
p=p->next;//两句顺序不能反
}
}
h=h->next;//h指向一开始的头结点q的位置,题目要求返回头指针,因此后移一位
return h;//返回头指针
}