在C语言中,可以通过文件操作函数将链表与文件结合起来。具体步骤如下:
typedef struct Node {
int data;
struct Node* next;
} Node;
Node* insert(Node* head, int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
} else {
Node* temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
return head;
}
Node* delete(Node* head, int data) {
Node* current = head;
Node* prev = NULL;
while (current != NULL) {
if (current->data == data) {
if (prev == NULL) { // 删除头节点
head = current->next;
} else {
prev->next = current->next;
}
free(current);
break;
}
prev = current;
current = current->next;
}
return head;
}
void writeToFile(Node* head, const char* filename) {
FILE* file = fopen(filename, "w");
if (file == NULL) {
printf("Failed to open file!\n");
return;
}
Node* current = head;
while (current != NULL) {
fprintf(file, "%d\n", current->data);
current = current->next;
}
fclose(file);
}
Node* readFromFile(const char* filename) {
FILE* file = fopen(filename, "r");
if (file == NULL) {
printf("Failed to open file!\n");
return NULL;
}
Node* head = NULL;
int data;
while (fscanf(file, "%d", &data) != EOF) {
head = insert(head, data);
}
fclose(file);
return head;
}
这样,就可以通过调用这些函数,将链表中的数据写入文件,或者从文件中读取数据到链表中。例如:
int main() {
Node* head = NULL;
// 插入数据到链表中
head = insert(head, 1);
head = insert(head, 2);
head = insert(head, 3);
// 将链表中的数据写入文件
writeToFile(head, "data.txt");
// 从文件中读取数据到链表
Node* newHead = readFromFile("data.txt");
// 打印链表中的数据
Node* current = newHead;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
// 释放链表内存
while (newHead != NULL) {
Node* temp = newHead;
newHead = newHead->next;
free(temp);
}
return 0;
}