c语言实现一个结构体链表数据库增删改查
时间: 2024-10-08 20:00:42 浏览: 46
在C语言中,我们可以使用结构体和指针来实现一个简单的链表数据库。这里我们将创建一个基本的"Student"结构体作为数据项,并用链表来存储。以下是核心的部分代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义学生结构体
typedef struct {
char name[50];
int id;
} Student;
// 链表节点结构体
typedef struct Node {
Student data;
struct Node* next;
} Node;
// 初始化链表头指针
Node* head = NULL;
// 插入操作 (添加新学生)
void insert(Student student) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (newNode != NULL) {
newNode->data = student;
newNode->next = head;
head = newNode;
printf("Student inserted successfully.\n");
} else {
printf("Memory allocation failed.\n");
}
}
// 删除操作 (按ID删除特定学生)
void delete(int id) {
Node* temp = head;
Node* prev = NULL;
while (temp != NULL && temp->data.id != id) {
prev = temp;
temp = temp->next;
}
if (temp == NULL) {
printf("Student not found in the list.\n");
} else {
if (prev == NULL) {
head = temp->next;
} else {
prev->next = temp->next;
}
free(temp);
printf("Student with ID %d deleted.\n", id);
}
}
// 修改操作 (更新学生信息)
void update(int id, const char* newName, int newId) {
Node* temp = head;
while (temp != NULL && temp->data.id != id) {
temp = temp->next;
}
if (temp == NULL) {
printf("Student not found in the list.\n");
} else {
strcpy(temp->data.name, newName);
temp->data.id = newId;
printf("Student with ID %d updated.\n", id);
}
}
// 查询操作 (查找并显示学生信息)
void search(int id) {
Node* temp = head;
while (temp != NULL) {
if (temp->data.id == id) {
printf("Name: %s, ID: %d\n", temp->data.name, temp->data.id);
break;
}
temp = temp->next;
}
if (temp == NULL) {
printf("Student not found in the list.\n");
}
}
int main() {
// 示例用法
insert({ "Alice", 101 });
search(101); // 查找
delete(101); // 删除
update(101, "Bob", 102); // 更新
return 0;
}
```
阅读全文