#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
typedef struct Node {
int data;
struct Node *next;
} Node, *Node_p;
// 创建新节点
Node_p createNode(int data) {
Node_p newNode = (Node_p)malloc(sizeof(Node));
if (!newNode) {
perror("Malloc failed");
exit(EXIT_FAILURE);
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// 添加节点到链表末尾
void appendNode(Node_p *head, int data) {
Node_p newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
return;
}
Node_p current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
// 打印链表
void printList(Node_p head) {
Node_p current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
// 将链表数据写入文件
void writeListToFile(Node_p head, const char *filename) {
FILE *file = fopen(filename, "w");
if (!file) {
perror("File opening failed");
return;
}
Node_p current = head;
while (current != NULL) {
fprintf(file, "%d\n", current->data);
current = current->next;
}
fclose(file);
}
// 从文件中读取数据并创建链表
Node_p readListFromFile(const char *filename) {
FILE *file = fopen(filename, "r");
if (!file) {
perror("File opening failed");
return NULL;
}
Node_p head = NULL;
int data;
while (fscanf(file, "%d", &data) != EOF) {
appendNode(&head, data);
}
fclose(file);
return head;
}
// 主函数
int main() {
Node_p myList = NULL;
// 随便搞点数据添加到链表中
appendNode(&myList, 5);
appendNode(&myList, 10);
appendNode(&myList, 15);
// 打印链表
printf("Original list:\n");
printList(myList);
// 将链表数据写入文件
writeListToFile(myList, "list_data.txt");
// 释放原始链表内存
Node_p temp;
while (myList != NULL) {
temp = myList;
myList = myList->next;
free(temp);
}
// 从文件中读取数据并重建链表
Node_p newList = readListFromFile("list_data.txt");
// 打印新链表
printf("List read from file:\n");
printList(newList);
// 释放新链表内存
while (newList != NULL) {
temp = newList;
newList = newList->next;
free(temp);
}
return 0;
}
2.29作业
最新推荐文章于 2024-11-02 20:41:42 发布