在上述代码的基础上,输入一个学号,在单链表上查找该学号的结点,找到,则删除该结点,找不到,则给出提示。用C语言编写
时间: 2024-03-25 15:36:48 浏览: 10
好的,我们可以在上述代码的基础上继续实现删除节点的功能。具体实现如下:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义学生结构体
struct Student {
char id[10]; // 学号
char name[20]; // 姓名
double score[3]; // 3门课程成绩
};
// 定义单链表结构体
struct ListNode {
struct Student data; // 存储数据
struct ListNode *next; // 指向下一个节点的指针
};
// 插入节点
void insert(struct ListNode **head, struct ListNode **tail, int pos, struct Student newStudent) {
// 创建新节点
struct ListNode *newNode = (struct ListNode *)malloc(sizeof(struct ListNode));
newNode->data = newStudent;
newNode->next = NULL;
// 插入到头部
if (pos == 0) {
newNode->next = *head;
*head = newNode;
if (*tail == NULL) {
*tail = *head;
}
return;
}
// 插入到尾部
if (pos == -1) {
if (*tail == NULL) {
*head = *tail = newNode;
} else {
(*tail)->next = newNode;
*tail = newNode;
}
return;
}
// 插入到指定位置
struct ListNode *p = *head;
int i = 0;
while (p != NULL && i < pos - 1) {
p = p->next;
i++;
}
if (p == NULL) {
printf("插入位置无效\n");
return;
}
newNode->next = p->next;
p->next = newNode;
}
// 删除节点
void delete(struct ListNode **head, struct ListNode **tail, char *id) {
struct ListNode *p = *head;
struct ListNode *prev = NULL;
while (p != NULL && strcmp(p->data.id, id) != 0) {
prev = p;
p = p->next;
}
if (p == NULL) {
printf("未找到该学号的节点\n");
return;
}
if (p == *head) {
*head = p->next;
if (*head == NULL) {
*tail = NULL;
}
} else {
prev->next = p->next;
if (p == *tail) {
*tail = prev;
}
}
free(p);
}
// 打印单链表
void printList(struct ListNode *head) {
struct ListNode *p = head;
while (p != NULL) {
printf("%s\t%s\t%.2f\t%.2f\t%.2f\n", p->data.id, p->data.name, p->data.score[0], p->data.score[1], p->data.score[2]);
p = p->next;
}
}
int main() {
struct ListNode *head = NULL;
struct ListNode *tail = NULL;
// 定义3个 Student 变量
struct Student stu1 = {"1001", "张三", {80, 85, 90}};
struct Student stu2 = {"1002", "李四", {75, 88, 92}};
struct Student stu3 = {"1003", "王五", {90, 92, 85}};
// 将 stu1 插入到表头
insert(&head, &tail, 0, stu1);
// 将 stu2 插入到表尾
insert(&head, &tail, -1, stu2);
// 将 stu3 插入到第二个位置
insert(&head, &tail, 1, stu3);
// 打印单链表
printf("插入节点后的单链表:\n");
printList(head);
// 输入一个学号,查找并删除该节点
char id[10];
printf("请输入要删除的学号:");
scanf("%s", id);
delete(&head, &tail, id);
// 打印单链表
printf("删除节点后的单链表:\n");
printList(head);
return 0;
}
```
这样,我们就可以在单链表上查找并删除指定学号的节点了。