|
发表于 2024-12-20 14:18:33
|
显示全部楼层
本楼为最佳答案

- // 链表节点的定义
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- // 定义链表节点
- typedef struct Node {
- int data;
- struct Node* next;
- } Node;
- // 创建一个新节点
- Node* createNode(int data) {
- Node* newNode = (Node*)malloc(sizeof(Node));
- if (!newNode) {
- printf("内存分配失败\n");
- exit(1);
- }
- newNode->data = data;
- newNode->next = NULL;
- return newNode;
- }
- // 将链表保存到文件中
- void saveLinkedListToFile(Node* head, const char* filename) {
- FILE* file = fopen(filename, "w");
- if (!file) {
- printf("无法打开文件 %s\n", filename);
- return;
- }
- Node* current = head;
- while (current != NULL) {
- fprintf(file, "%d\n", current->data);
- current = current->next;
- }
- fclose(file);
- printf("链表已保存到文件 %s\n", filename);
- }
- // 从文件中读取链表
- Node* readLinkedListFromFile(const char* filename) {
- FILE* file = fopen(filename, "r");
- if (!file) {
- printf("无法打开文件 %s\n", filename);
- return NULL;
- }
- Node* head = NULL;
- Node* tail = NULL;
- int data;
- while (fscanf(file, "%d", &data) != EOF) {
- Node* newNode = createNode(data);
- if (head == NULL) {
- head = newNode;
- tail = newNode;
- } else {
- tail->next = newNode;
- tail = newNode;
- }
- }
- fclose(file);
- printf("链表已从文件 %s 读取\n", filename);
- return head;
- }
- // 打印链表
- void printLinkedList(Node* head) {
- Node* current = head;
- while (current != NULL) {
- printf("%d -> ", current->data);
- current = current->next;
- }
- printf("NULL\n");
- }
- // 释放链表
- void freeLinkedList(Node* head) {
- Node* current = head;
- while (current != NULL) {
- Node* temp = current;
- current = current->next;
- free(temp);
- }
- }
- // 主函数
- int main() {
- // 创建一个链表
- Node* head = createNode(1);
- head->next = createNode(2);
- head->next->next = createNode(3);
- printf("原始链表: ");
- printLinkedList(head);
- // 保存链表到文件
- const char* filename = "linked_list.txt";
- saveLinkedListToFile(head, filename);
- // 释放原始链表
- freeLinkedList(head);
- // 从文件中读取链表
- head = readLinkedListFromFile(filename);
- printf("从文件读取的链表: ");
- printLinkedList(head);
- // 释放读取的链表
- freeLinkedList(head);
- return 0;
- }
复制代码 |
|