C语言建立一个含有10个结点的单链表,每个节点包括:学号、姓名、性别、年龄和一门课程的成绩。向原单链表中插入两个新结点。
时间: 2024-05-12 22:15:48 浏览: 96
以下是用 C 语言建立一个含有 10 个结点的单链表,每个节点包括:学号、姓名、性别、年龄和一门课程的成绩的代码。
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义节点
typedef struct student {
int id; // 学号
char name[20]; // 姓名
char sex[5]; // 性别
int age; // 年龄
int score; // 成绩
struct student *next; // 指向下一个节点的指针
} Student;
int main() {
int i;
Student *head, *p, *q;
// 创建链表
head = (Student *)malloc(sizeof(Student));
head->next = NULL;
p = head;
for (i = 0; i < 10; i++) {
q = (Student *)malloc(sizeof(Student));
q->id = i + 1;
sprintf(q->name, "%s%d", "Student", i + 1);
strcpy(q->sex, (i % 2 == 0) ? "M" : "F");
q->age = 18 + i % 3;
q->score = 60 + i % 41;
q->next = NULL;
p->next = q;
p = q;
}
// 输出链表
printf("原链表:\n");
p = head->next;
while (p != NULL) {
printf("%d %s %s %d %d\n", p->id, p->name, p->sex, p->age, p->score);
p = p->next;
}
// 插入新节点
Student *node1 = (Student *)malloc(sizeof(Student));
node1->id = 11;
strcpy(node1->name, "New Student1");
strcpy(node1->sex, "M");
node1->age = 20;
node1->score = 90;
node1->next = NULL;
p = head;
while (p->next != NULL) {
if (p->next->id > node1->id) {
node1->next = p->next;
p->next = node1;
break;
}
p = p->next;
}
Student *node2 = (Student *)malloc(sizeof(Student));
node2->id = 12;
strcpy(node2->name, "New Student2");
strcpy(node2->sex, "F");
node2->age = 21;
node2->score = 85;
node2->next = NULL;
p = head;
while (p->next != NULL) {
if (p->next->id > node2->id) {
node2->next = p->next;
p->next = node2;
break;
}
p = p->next;
}
// 输出链表
printf("插入新节点后的链表:\n");
p = head->next;
while (p != NULL) {
printf("%d %s %s %d %d\n", p->id, p->name, p->sex, p->age, p->score);
p = p->next;
}
// 释放内存
p = head;
while (p != NULL) {
q = p;
p = p->next;
free(q);
}
return 0;
}
```
这段代码首先创建一个含有 10 个节点的链表,然后插入两个新节点,并输出插入新节点后的链表。最后释放内存。
阅读全文