用C语言写出学生数据元素(学号1,2,3…10,姓名) 10个对数据元素进行查找、删除5、插入5的算法
时间: 2024-10-01 14:08:21 浏览: 29
在C语言中,为了管理学生数据元素,我们可以创建一个结构体来存储学号和姓名,然后使用链表作为数据结构来方便操作。这里是一个简单的例子,包含插入、查找和删除操作:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int student_id;
char name[20];
} Student;
typedef struct Node {
Student data;
struct Node* next;
} Node;
typedef struct {
Node* head;
} StudentList;
// 插入函数
void insert(StudentList* list, int id, const char* name) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data.student_id = id;
strcpy(newNode->data.name, name);
if(list->head == NULL) {
list->head = newNode;
} else {
Node* temp = list->head;
while(temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}
// 查找函数
Node* search(StudentList* list, int id) {
Node* temp = list->head;
while(temp != NULL) {
if(temp->data.student_id == id) {
return temp;
}
temp = temp->next;
}
return NULL; // 如果找不到,则返回NULL
}
// 删除函数
void delete(StudentList* list, int id) {
if(list->head == NULL) return;
if(list->head->data.student_id == id) {
Node* temp = list->head;
list->head = list->head->next;
free(temp);
return;
}
Node* prev = list->head;
Node* curr = list->head->next;
while(curr != NULL) {
if(curr->data.student_id == id) {
prev->next = curr->next;
free(curr);
return;
}
prev = curr;
curr = curr->next;
}
}
int main() {
StudentList list;
list.head = NULL;
// 插入示例
insert(&list, 1, "张三");
insert(&list, 5, "李四");
// 查找示例
Node* found = search(&list, 5);
if(found != NULL) {
printf("找到的学生ID %d 的名字是:%s\n", found->data.student_id, found->data.name);
} else {
printf("未找到学生ID %d\n", 5);
}
// 删除示例
delete(&list, 5);
return 0;
}
```
阅读全文