本题要求实现两个函数,一个将输入的学生成绩组织成单向链表;另一个将成绩低于某分数线的学生结点从链表中删除。
函数接口定义:
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() {
int num;
struct stud_node* head = (struct stud_node*)malloc(sizeof(struct stud_node));
head->next = NULL;
struct stud_node* curNode = head;
scanf("%d", &num);
while (num) {
struct stud_node* newNode = (struct stud_node*)malloc(sizeof(struct stud_node));
newNode->num = num;
scanf("%s", &newNode->name);
scanf("%d", &newNode->score);
newNode->next = NULL;
curNode->next = newNode;
curNode = newNode;
scanf("%d", &num);
}
return head;
}
struct stud_node* deletelist(struct stud_node* head, int min_score) {
struct stud_node* preNode = head;
struct stud_node* curNode = head->next;
while (curNode != NULL) {
if (curNode->score < min_score) {
struct stud_node* temp = curNode;
preNode->next = curNode->next;
curNode = curNode->next;
free(temp);
}
else {
curNode = curNode->next;
preNode = preNode->next;
}
}
return head->next;
}
注意点:
1.编译错误的原因1:本题只提交函数!!!如果把所有代码(main函数)都提交了会提示编译错误。
2.如果还是编译错误,那么看看你提交的是不是用c语言
如果是的话,检查你的结构体指针,c语言要struct stud_node*,而c++可以stud_node*
在用malloc函数时,也要加上struct:
struct stud_node* newList = (struct stud_node*)malloc(sizeof(struct stud_node));
这个错误编译器会输出:
3.free的位置问题
if (curNode->score < min_score) {
struct stud_node* temp = curNode;
preNode->next = curNode->next;
curNode = curNode->next;
free(temp);
}
我一开始写的是这样的顺序:
if (curNode->score < min_score) {
struct stud_node* temp = curNode;
preNode->next = curNode->next;
free(temp);
curNode = curNode->next;
}
这样是不行的,在执行free语句之前,temp与curNode指向的是同一个地址,如果先free(temp),那么curNode指向的地址也就没了,所以要先移动,后free
4.输入结束不了怎么办?
看createList函数:
while (num) {
struct stud_node* newNode = (struct stud_node*)malloc(sizeof(struct stud_node));
newNode->num = num;
scanf("%s", &newNode->name); //注意这里都要用取地址符
scanf("%d", &newNode->score);
newNode->next = NULL;
curNode->next = newNode;
curNode = newNode;
scanf("%d", &num); //这里是不是没写
}