#include <stdlib.h>
typedef struct student {
int num;
char name[20];
int score;
struct student* next;
} STU;
// 创建链表
STU* link_creat(STU* head, STU* p_new) {
if (head == NULL) {
p_new->next = NULL;
return p_new; // 返回新的头节点
} else {
STU* p_mov = head;
while (p_mov->next != NULL) {
p_mov = p_mov->next;
}
p_mov->next = p_new;
p_new->next = NULL;
}
return head; // 返回旧的头节点
}
void link_print(STU* head) {
STU* p_mov = head;
while (p_mov != NULL) {
printf("num=%d,name:%s,score=%d\n", p_mov->num, p_mov->name, p_mov->score);
p_mov = p_mov->next;
}
}
// 查找学号
STU* link_find_num(STU* head, int num) {
STU* p_mov = head;
while (p_mov != NULL) {
if (p_mov->num == num)
return p_mov;
p_mov = p_mov->next;
}
return NULL;
}
// 查找姓名
STU* link_find_name(STU* head, const char* name) {
STU* p_mov = head;
while (p_mov != NULL) {
if (strcmp(p_mov->name, name) == 0)
return p_mov;
p_mov = p_mov->next;
}
return NULL;
}
// 删除节点
STU* link_delete(STU* head, int num) {
if (head == NULL) {
printf("链表为空\n");
return head;
}
STU* pb = head;
STU* pf = NULL;
// 如果要删除的是头节点
if (pb->num == num) {
head = pb->next;
free(pb);
return head;
}
// 寻找要删除的节点
while (pb != NULL && pb->num != num) {
pf = pb;
pb = pb->next;
}
if (pb != NULL) { // 找到节点
pf->next = pb->next;
free(pb);
} else {
printf("没找到要删除的节点\n");
}
return head;
}
// 插入新节点
STU* link_insert(STU* head, STU* p_new) {
if (head == NULL || p_new->num < head->num) {
p_new->next = head;
return p_new; // 新的头节点
}
STU* pb = head;
STU* pf = NULL;
while (pb != NULL && p_new->num >= pb->num) {
pf = pb;
pb = pb->next;
}
p_new->next = pb;
if (pf != NULL) {
pf->next = p_new;
}
return head; // 返回旧的头节点
}
int main() {
int number;
scanf("%d", &number);
STU* head = NULL;
for (int i = 0; i < number; i++) {
STU* p_new = (STU*)malloc(sizeof(STU));
scanf("%d %s %d", &p_new->num, p_new->name, &p_new->score);
head = link_creat(head, p_new); // 更新头指针
}
// 示例:打印链表
link_print(head);
// 示例:查找并打印特定学号的学生信息
int search_num;
scanf("%d", &search_num);
STU* found = link_find_num(head, search_num);
if (found) {
printf("Found student: num=%d, name=%s, score=%d\n", found->num, found->name, found->score);
} else {
printf("Student not found.\n");
}
// 示例:删除特定学号的学生信息
int delete_num;
scanf("%d", &delete_num);
head = link_delete(head, delete_num); // 更新头指针
// 示例:插入新学生信息
STU* new_student = (STU*)malloc(sizeof(STU));
scanf("%d %s %d", &new_student->num, new_student->name, &new_student->score);
head = link_insert(head, new_student); // 更新头指针
// 最后打印链表查看结果
link_print(head);
return 0;
}```