因为之前c++以及数据结构有过学习,这里只是写个简单的程序,记录。
#include <stdio.h>
#include <stdlib.h>
#define LEN sizeof(struct student)
struct student {
int num;
float score;
struct student *next;
};
// 函数声明
struct student *creat();
struct student *del(struct student *head, int num);
void print(struct student *head);
struct student *insert(struct student *head, struct student *stu2);
int n; // 全局变量,记录学生数量
// 创建链表
struct student *creat() {
struct student *head = NULL, *p1, *p2;
int input_num;
float input_score;
do {
p1 = (struct student *)malloc(LEN);
if (p1 == NULL) {
fprintf(stderr, "Memory allocation failed.\n");
exit(1);
}
printf("Please input the num: ");
scanf("%d", &input_num);
if (input_num == 0) { // 假设输入0结束输入
free(p1); // 释放未使用的内存
break;
}
p1->num = input_num;
printf("Please enter the score: ");
scanf("%f", &input_score);
p1->score = input_score;
p1->next = NULL;
if (head == NULL) {
head = p1;
p2 = p1;
} else {
p2->next = p1;
p2 = p1;
}
n++;
} while (1);
return head;
}
// 删除指定节点
struct student *del(struct student *head, int num) {
struct student *p1, *p2;
p1 = head;
p2 = NULL; // 初始化为NULL
while (p1 != NULL && p1->num != num) {
p2 = p1;
p1 = p1->next;
}
if (p1 == NULL) {
printf("%d not been found!\n", num);
} else {
if (p2 == NULL) {
head = p1->next; // 删除的是头节点
} else {
p2->next = p1->next; // 删除中间或尾部节点
}
printf("Delete NO:%d succeed!\n", num);
n--;
free(p1); // 释放被删除节点的内存
}
return head;
}
// 打印链表
void print(struct student *head) {
struct student *p = head;
printf("There are %d record student!\n", n);
while (p != NULL) {
printf("num is: %d, score is: %f\n", p->num, p->score);
p = p->next;
}
}
// 插入节点
struct student *insert(struct student *head, struct student *stu2) {
struct student *p0, *p1, *p2;
p0 = stu2;
p1 = head;
p2 = NULL; // 初始化为NULL
if (head == NULL) {
head = p0;
p0->next = NULL;
} else {
while (p1 != NULL && p1->num < p0->num) {
p2 = p1;
p1 = p1->next;
}
if (p1 == head && p1->num >= p0->num) {
p0->next = head;
head = p0;
} else if (p1 != NULL) {
p2->next = p0;
p0->next = p1;
} else {
p1->next = p0;
p0->next = NULL;
}
}
n++;
return head;
}
int main() {
struct student *stu, *p, *stu2;
stu = creat();
p = stu;
print(p);
printf("Please enter the num to delete: ");
scanf("%d", &n);
p = del(p, n);
print(p);
printf("Please enter the num to insert: ");
scanf("%d", &n); // 注意这里使用n作为临时变量
stu2 = (struct student *)malloc(LEN);
if (stu2 == NULL) {
fprintf(stderr, "Memory allocation failed.\n");
return 1;
}
printf("Please enter the score to insert: ");
scanf("%f", &stu2->score);
stu2->num = n; // 插入前读取的num赋值给新节点
p = insert(p, stu2);
print(p);
// 释放链表内存
while (p != NULL) {
struct student *temp = p;
p = p->next;
free(temp);
}
return 0;
}
结果: