c++如何将单链表数据存入文件中
作者:野牛程序员:2023-11-26 12:04:04 C++阅读 3011
使用C++将单链表数据存入文件的一种常见方法是使用文件流(fstream)。以下是一个简单的示例,演示如何将单链表的数据存储到文件中:
#include <iostream>
#include <fstream>
// 单链表节点的定义
struct Node {
int data;
Node* next;
Node(int value) : data(value), next(nullptr) {}
};
// 函数声明
void saveListToFile(Node* head, const char* filename);
Node* createSampleList();
int main() {
// 创建一个示例单链表
Node* myList = createSampleList();
// 将单链表数据保存到文件中
saveListToFile(myList, "list_data.txt");
std::cout << "数据已保存到文件中。\\n";
// 释放单链表的内存
Node* current = myList;
Node* nextNode;
while (current != nullptr) {
nextNode = current->next;
delete current;
current = nextNode;
}
return 0;
}
// 将单链表数据保存到文件
void saveListToFile(Node* head, const char* filename) {
std::ofstream file(filename);
if (file.is_open()) {
Node* current = head;
// 遍历链表并将数据写入文件
while (current != nullptr) {
file << current->data << " ";
current = current->next;
}
file.close();
} else {
std::cerr << "无法打开文件:" << filename << std::endl;
}
}
// 创建一个示例单链表
Node* createSampleList() {
Node* head = new Node(1);
head->next = new Node(2);
head->next->next = new Node(3);
head->next->next->next = new Node(4);
head->next->next->next->next = new Node(5);
return head;
}这个示例包括了一个简单的Node结构表示单链表的节点,以及saveListToFile函数用于将链表数据保存到文件中。在main函数中,首先创建了一个示例的单链表,然后调用saveListToFile函数将数据保存到名为 "list_data.txt" 的文件中。最后,释放了单链表的内存。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

- 上一篇:c++如何把一个链表加到另一个链表后面
- 下一篇:Python链表储存用法介绍
