创建动态链表并打印链表内容。要求通过键盘读入学生的学号和分数,当输入的学号为0时表示链表创建结束,并将读入的学生学号和成绩打印输出。下面程序中存在比较隐蔽的错误,请通过分析和调试程序,发现并改正程序中的错误。改错时不能改变程序原有的意图。 注意:将修改后的完整的源程序写在答题区内。 #include <stdio.h> #define SIZE sizeof(struct node) struct node { long num; float score; struct node *next; } int main() { int n = 0; struct node *head = NULL, *p1, *p2; p1 = p2 = (struct node*)malloc(SIZE); printf("Input %d node data:\n", n + 1); scanf("%d%f", &p1->num, &p1->score); while (p1->num != 0) { if (++n == 1) head = p1; else p2->next = p1; p1 = p2; p1 = (struct node*)malloc(SIZE); printf("Input %d node data:\n", n + 1); scanf("%d%f", &p1->num, &p1->score); } free(p1); printf("Prit list:\n"); p2->next = NULL; if (head != NULL) { p2=head; while (p1 != NULL) { printf("num:%d\tscore:%.2f\n", p1->num, p1->score); p1 = p1->next; } } return 0; }
时间: 2023-07-14 13:14:31 浏览: 49
修改后的程序如下:
```
#include <stdio.h>
#include <stdlib.h>
#define SIZE sizeof(struct node)
struct node {
long num;
float score;
struct node *next;
};
int main() {
int n = 0;
struct node *head = NULL, *p1, *p2;
p1 = p2 = (struct node*)malloc(SIZE);
printf("Input %d node data:\n", n + 1);
scanf("%ld%f", &p1->num, &p1->score);
while (p1->num != 0) {
if (++n == 1) {
head = p1;
} else {
p2->next = p1;
}
p2 = p1;
p1 = (struct node*)malloc(SIZE);
printf("Input %d node data:\n", n + 1);
scanf("%ld%f", &p1->num, &p1->score);
}
free(p1);
printf("Print list:\n");
p2->next = NULL;
if (head != NULL) {
p1 = head;
while (p1 != NULL) {
printf("num:%ld\tscore:%.2f\n", p1->num, p1->score);
p1 = p1->next;
}
}
return 0;
}
```
主要的修改如下:
1. 在头文件中添加 stdlib.h,以便使用 malloc 和 free 函数。
2. 在结构体定义后添加分号。
3. 在输入学号和分数时,修改为用 %ld 格式符读入 long 类型的数据。
4. 在创建链表时,将 p2 赋值为 p1,遍历链表时用 p1 变量。
5. 在遍历链表前,将 p2->next 设为 NULL,以防止输出链表时出现不可预知的错误。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)