建立一个5名学生信息的单向链表,每个结点包括学号、姓名、性别、年龄,采用插入排序方式,按学号对其从小到大排列
时间: 2024-01-07 22:05:02 浏览: 79
以下是一个简单的实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义链表节点结构体
typedef struct student {
int id;
char name[20];
char sex[10];
int age;
struct student* next;
} Student;
// 定义链表头指针
Student* head = NULL;
// 插入节点函数(按学号从小到大排序)
void insertNode(int id, char name[], char sex[], int age) {
Student* newNode = (Student*)malloc(sizeof(Student));
newNode->id = id;
strcpy(newNode->name, name);
strcpy(newNode->sex, sex);
newNode->age = age;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
} else {
if (head->id > id) {
newNode->next = head;
head = newNode;
} else {
Student* current = head;
while (current->next != NULL && current->next->id < id) {
current = current->next;
}
newNode->next = current->next;
current->next = newNode;
}
}
}
// 输出链表函数
void printList() {
Student* current = head;
while (current != NULL) {
printf("id: %d, name: %s, sex: %s, age: %d\n", current->id, current->name, current->sex, current->age);
current = current->next;
}
}
int main() {
// 插入节点并排序
insertNode(2, "Tom", "male", 20);
insertNode(1, "Jerry", "female", 21);
insertNode(4, "Lucy", "female", 19);
insertNode(3, "Bob", "male", 22);
insertNode(5, "Alice", "female", 18);
// 输出链表
printList();
return 0;
}
```
这个程序会创建一个包含5名学生信息的单向链表,每个节点包括学号、姓名、性别和年龄。它会采用插入排序的方式,按学号从小到大排列。最后,它会输出整个链表的内容。
阅读全文