输入一个整数n,再使用malloc函数申请nsizeof(struct Student)大小的内存空间,对n个struct Student类型的元素赋值,并显示。使用free函数释放该内存空间,在此基础上,为结构体struct Item类型增加struct Item next成员。并以此为结点,使用malloc函数动态建立多项式单链表。程序结束前使用free函数释放单链表所有结点。用c语言编写且有主函数,输出完整代码
时间: 2024-02-18 10:06:03 浏览: 67
c代码-编程实现:输入10个学生的6门课成绩,分别求出每个学生的平均成绩。
5星 · 资源好评率100%
好的,这是您的问题的答案,代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
struct Student {
char name[20];
int age;
};
struct Item {
double coef;
int exp;
struct Item *next;
};
void display_students(struct Student *p, int n) {
for (int i = 0; i < n; i++) {
printf("Student %d: Name: %s, Age: %d\n", i+1, p[i].name, p[i].age);
}
}
void free_students(struct Student *p) {
free(p);
}
struct Item* create_node(double coef, int exp) {
struct Item *node = (struct Item*) malloc(sizeof(struct Item));
node->coef = coef;
node->exp = exp;
node->next = NULL;
return node;
}
void add_node(struct Item **head, double coef, int exp) {
struct Item *new_node = create_node(coef, exp);
if (*head == NULL) {
*head = new_node;
} else {
struct Item *p = *head;
while (p->next != NULL) {
p = p->next;
}
p->next = new_node;
}
}
void display_poly(struct Item *head) {
struct Item *p = head;
while (p != NULL) {
printf("%.2fx^%d ", p->coef, p->exp);
p = p->next;
if (p != NULL) {
printf("+ ");
}
}
printf("\n");
}
void free_poly(struct Item *head) {
struct Item *p = head;
while (p != NULL) {
struct Item *q = p;
p = p->next;
free(q);
}
}
int main() {
int n;
printf("Input the number of Students: ");
scanf("%d", &n);
struct Student *students = (struct Student*) malloc(n * sizeof(struct Student));
for (int i = 0; i < n; i++) {
printf("Input the name of Student %d: ", i+1);
scanf("%s", students[i].name);
printf("Input the age of Student %d: ", i+1);
scanf("%d", &students[i].age);
}
printf("Displaying students info:\n");
display_students(students, n);
free_students(students);
struct Item *head = NULL;
add_node(&head, 2.5, 3);
add_node(&head, 1.2, 2);
add_node(&head, 3.4, 1);
add_node(&head, 1.0, 0);
printf("Displaying polynomial: ");
display_poly(head);
free_poly(head);
return 0;
}
```
希望能够帮到您!
阅读全文