用c语言写定义数据结构,借助for循环和插入算法编写一段程序,逐个输入学生信息,按成绩由高到低形成有序线性表(需要在插入过程中完成排序)。分别输出所建立线性表的数据域和last值。
时间: 2024-02-28 22:57:12 浏览: 91
好的,下面是一个示例程序,实现了上述要求:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_STUDENT_NUM 100
typedef struct Student {
char name[20];
int score;
} Student;
typedef struct ListNode {
Student data;
int next;
} ListNode;
ListNode list[MAX_STUDENT_NUM];
int last = -1;
int insert(Student s) {
int p = -1, q = 0;
while (q != -1 && s.score < list[q].data.score) {
p = q;
q = list[q].next;
}
int r = rand() % MAX_STUDENT_NUM;
while (list[r].next != -1) {
r = rand() % MAX_STUDENT_NUM;
}
list[r].data = s;
list[r].next = q;
if (p == -1) {
last = r;
} else {
list[p].next = r;
}
return r;
}
void print_list() {
printf("Data: ");
int p = list[last].next;
while (p != -1) {
printf("%s(%d) ", list[p].data.name, list[p].data.score);
p = list[p].next;
}
printf("\nLast: %d\n", last);
}
int main() {
int n;
printf("Enter the number of students: ");
scanf("%d", &n);
printf("Enter the student names and scores:\n");
for (int i = 0; i < n; i++) {
Student s;
scanf("%s%d", s.name, &s.score);
insert(s);
}
print_list();
return 0;
}
```
这个程序定义了两个数据结构,`Student` 表示学生,`ListNode` 表示链表节点。其中,`ListNode` 的 `data` 成员是一个 `Student`,`next` 成员是指向下一个节点的指针。此外,程序还定义了一个大小为 `MAX_STUDENT_NUM` 的 `list` 数组,用于存储链表节点,以及一个 `last` 变量,表示链表的尾节点。
插入操作的实现比较复杂。我们需要先找到插入位置,然后随机选择一个空闲节点,将新节点插入到这个位置。为了避免节点数量过多,我们使用了一个简单的随机化算法:每次插入时,随机选择一个节点,如果这个节点已经被占用,则继续随机选择下一个节点,直到找到一个空闲节点。
最后,我们在 `main` 函数中逐个输入学生信息,并调用 `insert` 函数来插入节点。插入完成后,调用 `print_list` 函数输出链表的数据域和 `last` 值。
注意,这个程序没有对输入进行任何检查,如果输入格式不正确或者节点数量超过 `MAX_STUDENT_NUM`,程序会出现未定义行为。实际应用中,我们应该加入相应的检查和错误处理机制。
阅读全文
相关推荐
















