鱼C论坛

 找回密码
 立即注册
查看: 1301|回复: 4

[已解决]如何把链表保存到文件中并且读取?

[复制链接]
发表于 2024-12-20 14:18:48 | 显示全部楼层
在保存链表到文件和从文件中读取链表时,确保每个节点的数据结构没有丢失至关重要。以下是一个基本的步骤,可以帮助你实现这个功能:

1. **定义链表节点:**
  1. class Node:
  2.     def __init__(self, data):
  3.         self.data = data
  4.         self.next = None
复制代码


2. **将链表保存到文件:**
   - 遍历链表,将每个节点的数据写入文件中。
   - 你可以选择用简单的文本格式或更复杂的格式(如序列化)来存储。

  1. def save_linked_list_to_file(head, filename):
  2.     with open(filename, 'w') as file:
  3.         current = head
  4.         while current:
  5.             file.write(str(current.data) + '\n')
  6.             current = current.next
复制代码


3. **从文件读取链表:**
   - 从文件中读取每一行数据,创建新的链表节点,并将其添加到链表中。

  1. def read_linked_list_from_file(filename):
  2.     with open(filename, 'r') as file:
  3.         head = None
  4.         current = None
  5.         for line in file:
  6.             data = line.strip()
  7.             new_node = Node(data)
  8.             if not head:
  9.                 head = new_node
  10.                 current = head
  11.             else:
  12.                 current.next = new_node
  13.                 current = current.next
  14.     return head
复制代码


4. **使用示例:**

  1. # 创建一个简单的链表 1 -> 2 -> 3
  2. head = Node(1)
  3. head.next = Node(2)
  4. head.next.next = Node(3)

  5. # 保存链表到文件
  6. save_linked_list_to_file(head, 'linked_list.txt')

  7. # 从文件读取链表
  8. new_head = read_linked_list_from_file('linked_list.txt')

  9. # 遍历新链表,打印数据
  10. current = new_head
  11. while current:
  12.     print(current.data)
  13.     current = current.next
复制代码


通过上述步骤,你应该可以正确地保存和读取链表。如果数据类型比较复杂,考虑使用Python的`pickle`模块进行序列化和反序列化。注意,如果使用文本格式保存,确保所有数据都可以用字符串表达,并且在读取时能够正确转换回原始数据类型。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2024-12-20 14:24:59 | 显示全部楼层


在C语言中,可以通过文件操作将链表保存到文件,然后读取回来构建链表。以下是一个简单的示例程序:

1. **定义链表节点结构:**

  1. typedef struct Node {
  2.     int data;
  3.     struct Node* next;
  4. } Node;
复制代码


2. **保存链表到文件:**

  1. void saveLinkedListToFile(Node* head, const char* filename) {
  2.     FILE* file = fopen(filename, "w");
  3.     if (!file) {
  4.         printf("无法打开文件。\n");
  5.         return;
  6.     }
  7.     Node* current = head;
  8.     while (current != NULL) {
  9.         fprintf(file, "%d\n", current->data);
  10.         current = current->next;
  11.     }
  12.     fclose(file);
  13. }
复制代码


3. **从文件读取链表:**

  1. Node* readLinkedListFromFile(const char* filename) {
  2.     FILE* file = fopen(filename, "r");
  3.     if (!file) {
  4.         printf("无法打开文件。\n");
  5.         return NULL;
  6.     }

  7.     Node* head = NULL;
  8.     Node* current = NULL;

  9.     int data;
  10.     while (fscanf(file, "%d", &data) != EOF) {
  11.         Node* newNode = (Node*)malloc(sizeof(Node));
  12.         newNode->data = data;
  13.         newNode->next = NULL;

  14.         if (head == NULL) {
  15.             head = newNode;
  16.             current = head;
  17.         } else {
  18.             current->next = newNode;
  19.             current = current->next;
  20.         }
  21.     }
  22.     fclose(file);
  23.     return head;
  24. }
复制代码


4. **使用示例:**

  1. int main() {
  2.     // 创建简单链表 1 -> 2 -> 3
  3.     Node* head = (Node*)malloc(sizeof(Node));
  4.     head->data = 1;
  5.     head->next = (Node*)malloc(sizeof(Node));
  6.     head->next->data = 2;
  7.     head->next->next = (Node*)malloc(sizeof(Node));
  8.     head->next->next->data = 3;
  9.     head->next->next->next = NULL;

  10.     // 保存链表到文件
  11.     saveLinkedListToFile(head, "linked_list.txt");

  12.     // 从文件读取链表
  13.     Node* newHead = readLinkedListFromFile("linked_list.txt");

  14.     // 遍历新链表,打印数据
  15.     Node* current = newHead;
  16.     while (current != NULL) {
  17.         printf("%d ", current->data);
  18.         Node* temp = current;
  19.         current = current->next;
  20.         free(temp);  // 释放节点内存
  21.     }
  22.     printf("\n");

  23.     // 逐个释放最初分配的节点内存
  24.     current = head;
  25.     while (current != NULL) {
  26.         Node* temp = current;
  27.         current = current->next;
  28.         free(temp);
  29.     }

  30.     return 0;
  31. }
复制代码


在上述程序中,我们先定义了链表节点的结构体,然后实现了两个函数来保存和读取链表。要记得释放动态分配的内存以避免内存泄漏。请根据实际需求调整代码,例如数据类型和文件名。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-9-21 02:43

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表