实验11-2-2 学生成绩链表处理 (20 分)

实验11-2-2 学生成绩链表处理 (20 分)

本题要求实现两个函数,一个将输入的学生成绩组织成单向链表;另一个将成绩低于某分数线的学生结点从链表中删除。

函数接口定义:

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,*tail;
	p=( struct stud_node*)malloc(sizeof(struct stud_node));
	int i=0;
	scanf("%d",&p->num);
	while(p->num!=0){
		i++;
			scanf("%s %d",&p->name,&p->score);
		if(i==1){
			head=p;
			tail=p;  //构建结点 即head 需要把开头与尾巴放一起
			tail->next=NULL;
		}
		else {
			tail->next=p; //构建body  关键在于使得尾巴指向下一链接而不是NULL 
			tail=p;// 然后把尾巴换成指向的下一个连接,即让尾巴为最后一个
			tail->next=NULL;	 //重复让最后一个链接指向NULL 
		}
	p=( struct stud_node*)malloc(sizeof( struct stud_node));//重新申请一块新的p链接 
	scanf("%d",&p->num);
	}
	 return head;
}
struct stud_node *deletelist( struct stud_node *head, int min_score ){
	struct stud_node *n1,*n2;//构建n1 ,n2,其中n1指现在对应的,n2指下一个,利用->next 可以得
	if(head==NULL) return NULL;    //中间的,然后把中间free 链接前后
	while(head!=NULL&&head->score<min_score){ 
	  	n2=head;              
		  head=head->next;//先解决开头是否需要free
		  free(n2);	
	  }
	  if(head==NULL) return NULL;//防止free后全部都被干掉 开头也是空的
	  n1=head;
	  n2=head->next;//注意让他们指向前后
	 while(n2!=NULL) { 
	  	if(n2->score<min_score){//判断是否符合删除要求
	  	n1->next=n2->next;//n2->next指向的是于n1间隔1个的链接
		 free(n2);
		 n2=n1->next;
		  }
		  else { //如果没有就让n1=n2后移一位
		  
		   n1=n2;
		  n2=n2->next;}
	  }
	
	return head;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值