C语言-学生成绩链表处理

C语言-学生成绩链表处理,第1张

题目详情

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


文章目录

  • 一、输入样例
  • 二、输出样例
  • 三、代码展示
  • 四、思路体现
  • 五、难点记录

一、输入样例

输入为若干个学生的信息(学号、姓名、成绩),组织成单向链表,当输入学号为0时结束。

之后继续输入分数线(成绩低于此分数线的学生从结点链表中删除);

1 zhang 78
2 wang 80
3 li 75
4 zhao 85
0
80
二、输出样例

输出成绩低于高入分数线的学生;

2 wang 80
4 zhao 85
三、代码展示

1)函数接口定义:

struct stud_node *createlist();
struct stud_node *deletelist( struct stud_node *head, int min_score );

2) 裁判测试程序样例:

#include 
#include 

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;
}

/* 你的代码将被嵌在这里 */

3) /* 你的代码将被嵌在这里 */

/* 你的代码将被嵌在这里 */
struct stud_node *createlist()
{
	struct stud_node *head,*tail,*p;
	head = tail = NULL;        
	int num,score;
	char name[20];
	scanf("%d",&num);        //输入学号
	while(num != 0){
		scanf("%s %d",name,&score);
		p = (struct stud_node*)malloc(sizeof(struct stud_node));        
        //开辟动态空间,注意,free()函数只能释放开辟的动态空间
		p->num = num;        
		p->score = score;
		strcpy(p->name,name);        
		if(head == NULL){        //若是头结点为空的话,那么使头节点head等于p
			head = p;
		}else {        //若是头节点不为空的话,那么尾结点的下一个结点等于p
			tail->next = p;            
		}tail = p;       
        /*
          尾结点意为最后一个结点,而我们在上个步骤在尾结点之后又增加了一个结点p
          因此我们需要移动尾结点的指向,使尾结点指向p
        */
		scanf("%d",&num);
	}return head;        

}
struct stud_node *deletelist( struct stud_node *head, int min_score )
{
	struct stud_node *ptr1,*ptr2;
	while((head != NULL) && (head->score < min_score)){    
		ptr1 = head;
		head = head->next;
		free(ptr1);
	}if(head == NULL)         //当所有的成绩小于分数线时
		return NULL;
	ptr1 = head;        
	ptr2 = head->next;
	while(ptr2 != NULL){
		if((ptr2->score)next = ptr2->next;
			free(ptr2);
		}else
			ptr1 = ptr2;
		ptr2 = ptr1->next;
	}return head;
}
四、思路体现

重点记录如何删除结点:定义两个结构指针*ptr1,*ptr2,使它们一直指向相邻的两个结点(即ptr1->next = ptr2),利用指针ptr2进行遍历链表,当ptr2到了某个分数低于分数线的结点时,先使ptr1->next = ptr1->next,然后释放指针ptr2(free(ptr2)),最后继续使ptr2成为ptr1的下一个结点,即ptr2 = ptr1->next;

五、难点记录

理清楚删除结点的过程

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/788942.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-05
下一篇2022-05-05

发表评论

登录后才能评论

评论列表(0条)

    保存