题目:
本题要求实现两个函数,一个将输入的学生成绩组织成单向链表;另一个将成绩低于某分数线的学生结点从链表中删除。
函数接口定义:
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 *p,*head=NULL,*tail=NULL;
int a;
scanf("%d",&a); //暂存第一个学号
while(a!=0){
p=(struct stud_node*)malloc(sizeof(struct stud_node)); //学号不为零,申请空间
p->num=a;
scanf(" %s %d",p->name,&p->score);
if(head==NULL){ //如果链表为空,初始化链表
head=tail=p;
}
else{ //链表不为空,尾插法插入新的学生信息
tail->next=p;
tail=p;
tail->next=NULL;
}
scanf("%d",&a); //暂存下一个学号
}
return head; //返回头指针
}
struct stud_node *deletelist( struct stud_node *head, int min_score ){
struct stud_node *p1,*p2;
if(head==NULL){ //注意:链表为空则返回空
return NULL;
}
while(head!=NULL){ //先特殊处理第一个结点
if(head->score < min_score){ //第一个结点小于最小成绩
if(head->next != NULL){ //第一个结点后面不为空
head=head->next; //删除第一个,头结点指向下一个结点
}
else{ //第一个结点后面为空
return NULL; //直接删除第一个,返回空
}
}
else{ //第一个结点大于最小成绩
break; //退出
}
}
p1=head; //p1指向最新检测的要保留的结点
p2=head->next; //p2指向即将检测的结点
while(p2 != NULL){ //指向NULL则说明链表已检测完,可以直接返回头结点
while(p2->score < min_score){ //寻找下一个应该保留的结点
if(p2->next != NULL){ //下个结点不为空,继续检测下一个结点
p2=p2->next;
}
else{ //下个结点为空,将上一个可以保留的结点的后继指针指向空,返回头结点
p1->next=NULL;
return head;
}
} //退出循环表示找到下一个可以保留的结点
p1->next=p2; //将上一个可以保留的结点的后继指针指向该结点
p1=p2; //更新最新的可以保留的结点
p2=p2->next; //更新下一个需要检测的结点
}
return head;
}
后续:
struct stud_node *createlist(){
int a;
struct stud_node *p,*head=NULL,*tail=NULL;
scanf("%d",&a);
while(a!=0){
p=(struct stud_node*)malloc(sizeof(struct stud_node));
p->num=a;
scanf("%s %d",p->name,&p->score);
if(head==NULL){
head=tail=p;
tail->next=NULL;
}
else{
tail->next=p;
tail=p;
tail->next=NULL;
}
scanf("%d",&a);
}
return head;
}
struct stud_node *deletelist( struct stud_node *head, int min_score ){
struct stud_node *p;
while(head!=NULL && head->score < min_score){
head=head->next;
}
if(head==NULL){
return NULL;
}
p=head;
while(p->next!=NULL){
if(p->next->score < min_score){
struct stud_node *temp=p->next;
p->next=p->next->next;
free(temp);
}
else{
p=p->next;
}
}
return head;
}