将链表中数据存入文件中
时间: 2023-05-17 08:07:33 浏览: 83
可以使用文件流将链表中的数据存入文件中。具体实现方式可以参考以下代码:
```c++
#include <iostream>
#include <fstream>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
void saveListToFile(ListNode* head, string filename) {
ofstream outfile(filename);
if (!outfile) {
cout << "Failed to open file " << filename << endl;
return;
}
while (head) {
outfile << head->val << " ";
head = head->next;
}
outfile.close();
cout << "List saved to file " << filename << endl;
}
int main() {
ListNode* head = new ListNode(1);
head->next = new ListNode(2);
head->next->next = new ListNode(3);
head->next->next->next = new ListNode(4);
head->next->next->next->next = new ListNode(5);
saveListToFile(head, "list.txt");
return 0;
}
```
在上面的代码中,我们定义了一个链表结构体 `ListNode`,并实现了一个函数 `saveListToFile`,该函数接受两个参数,一个是链表的头指针 `head`,另一个是要保存的文件名 `filename`。函数中使用文件流 `ofstream` 将链表中的每个节点的值写入文件中,最后关闭文件流。在 `main` 函数中,我们创建了一个链表,并将其保存到文件 `list.txt` 中。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)