|
发表于 2024-12-20 14:24:59
|
显示全部楼层
在C语言中,可以通过文件操作将链表保存到文件,然后读取回来构建链表。以下是一个简单的示例程序:
1. **定义链表节点结构:**
- typedef struct Node {
- int data;
- struct Node* next;
- } Node;
复制代码
2. **保存链表到文件:**
- void saveLinkedListToFile(Node* head, const char* filename) {
- FILE* file = fopen(filename, "w");
- if (!file) {
- printf("无法打开文件。\n");
- return;
- }
- Node* current = head;
- while (current != NULL) {
- fprintf(file, "%d\n", current->data);
- current = current->next;
- }
- fclose(file);
- }
复制代码
3. **从文件读取链表:**
- Node* readLinkedListFromFile(const char* filename) {
- FILE* file = fopen(filename, "r");
- if (!file) {
- printf("无法打开文件。\n");
- return NULL;
- }
- Node* head = NULL;
- Node* current = NULL;
- int data;
- while (fscanf(file, "%d", &data) != EOF) {
- Node* newNode = (Node*)malloc(sizeof(Node));
- newNode->data = data;
- newNode->next = NULL;
- if (head == NULL) {
- head = newNode;
- current = head;
- } else {
- current->next = newNode;
- current = current->next;
- }
- }
- fclose(file);
- return head;
- }
复制代码
4. **使用示例:**
- int main() {
- // 创建简单链表 1 -> 2 -> 3
- Node* head = (Node*)malloc(sizeof(Node));
- head->data = 1;
- head->next = (Node*)malloc(sizeof(Node));
- head->next->data = 2;
- head->next->next = (Node*)malloc(sizeof(Node));
- head->next->next->data = 3;
- head->next->next->next = NULL;
- // 保存链表到文件
- saveLinkedListToFile(head, "linked_list.txt");
- // 从文件读取链表
- Node* newHead = readLinkedListFromFile("linked_list.txt");
- // 遍历新链表,打印数据
- Node* current = newHead;
- while (current != NULL) {
- printf("%d ", current->data);
- Node* temp = current;
- current = current->next;
- free(temp); // 释放节点内存
- }
- printf("\n");
- // 逐个释放最初分配的节点内存
- current = head;
- while (current != NULL) {
- Node* temp = current;
- current = current->next;
- free(temp);
- }
- return 0;
- }
复制代码
在上述程序中,我们先定义了链表节点的结构体,然后实现了两个函数来保存和读取链表。要记得释放动态分配的内存以避免内存泄漏。请根据实际需求调整代码,例如数据类型和文件名。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|