本题要求实现两个函数,一个将输入的学生成绩组织成单向链表;另一个将成绩低于某分数线的学生结点从链表中删除。
函数接口定义:
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 *head=NULL,*tail=NULL,*p=NULL;
int num;
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=p;
else tail->next=p;
tail=p;
scanf("%d",&num);
}
return head;
}
struct stud_node *deletelist( struct stud_node *head, int min_score )
{
struct stud_node *p1,*p2;
p1=p2=head;
while(head!=NULL&&head->score<min_score)
{
head=head->next;
p1=p2=head;
}
while(p2!=NULL)
{
p2=p2->next;
if(p2==NULL) return head;
else if(p2->score<min_score)
{
p1->next=p2->next;
p2=p1;
}
else p1=p1->next;
}
return head;
}
输入方式类似,先判断学号,再储存和建立链表。删除时还是首先考虑首位删除的情况,接下来让p2先移到下一位进行判断,若小于则p1直接到p2的下一位去(跳过p2指向的这个结点),否则p1顺移一位即可。其实链表的建立与删除核心思想就是那样,只是会在判断条件等细节上加以考察,首先搞清基本思想,之后再想办法完成题目要求。