学生按学号排序插入链表
时间: 2023-07-11 07:23:49 浏览: 59
好的,这是一个比较常见的链表操作,我可以为您提供一个基本的思路:
1. 首先需要定义一个链表结构体,包含学号和其他需要的信息。
2. 然后需要定义一个插入函数,用于将新的节点插入到链表中。这个函数需要接收一个指向链表头节点的指针,以及新节点需要插入的位置。
3. 接下来,我们需要遍历链表,找到插入位置的前一个节点,如果找到了该节点,则将新节点插入到该位置。如果没有找到该节点,则说明新节点应该插入到链表的末尾。
4. 最后,记得要释放掉不再使用的内存空间。
下面是一个简单的 C 语言示例代码:
```c
typedef struct student {
int id;
char name[20];
struct student* next;
} Student;
void insert(Student** head, int id, char* name) {
Student* new_node = (Student*)malloc(sizeof(Student));
new_node->id = id;
strcpy(new_node->name, name);
new_node->next = NULL;
if (*head == NULL || (*head)->id >= new_node->id) {
new_node->next = *head;
*head = new_node;
}
else {
Student* current = *head;
while (current->next != NULL && current->next->id < new_node->id) {
current = current->next;
}
new_node->next = current->next;
current->next = new_node;
}
}
int main() {
Student* head = NULL;
insert(&head, 1001, "Tom");
insert(&head, 1003, "John");
insert(&head, 1002, "Bob");
insert(&head, 1005, "Alice");
insert(&head, 1004, "Mary");
// 遍历链表输出结果
Student* current = head;
while (current != NULL) {
printf("id: %d, name: %s\n", current->id, current->name);
current = current->next;
}
// 释放链表内存空间
current = head;
while (current != NULL) {
Student* temp = current;
current = current->next;
free(temp);
}
return 0;
}
```
在这个示例代码中,我们首先定义了一个 `Student` 结构体,包含学号和姓名等信息,并且定义了一个插入函数 `insert`,将新节点插入到链表中。在插入函数中,我们使用了一个指向指针的指针,因为需要修改链表头节点的值。
在主函数中,我们调用 `insert` 函数插入了 5 个节点,然后使用 while 循环遍历链表,输出每个节点的学号和姓名。最后,我们释放了链表的内存空间,避免内存泄漏。