c++文件的读取和写入与链表
时间: 2024-03-27 07:41:00 浏览: 14
读取和写入文件可以通过fstream库中的ifstream和ofstream来实现。具体步骤如下:
1. 打开文件并创建文件流对象
```c++
ifstream inFile;
inFile.open("input.txt"); // 打开输入文件流
ofstream outFile;
outFile.open("output.txt"); // 打开输出文件流
```
2. 读取文件内容或写入内容
```c++
// 读取文件内容
int x;
inFile >> x;
// 写入内容
outFile << "Hello World!";
```
3. 关闭文件流对象
```c++
inFile.close();
outFile.close();
```
链表是一种常用的数据结构,可以通过指针来实现。一般包括一个节点结构体和一个链表结构体,具体实现如下:
```c++
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
class LinkedList {
public:
LinkedList();
~LinkedList();
void addNode(int val);
void deleteNode(int val);
void printList();
private:
ListNode* head;
};
```
其中,addNode函数用于向链表中添加节点,deleteNode函数用于删除链表中的节点,printList函数用于打印链表中的所有节点。具体实现可以参考下面的代码:
```c++
LinkedList::LinkedList() {
head = new ListNode(-1);
}
LinkedList::~LinkedList() {
ListNode* cur = head;
while (cur != NULL) {
ListNode* tmp = cur;
cur = cur->next;
delete tmp;
}
}
void LinkedList::addNode(int val) {
ListNode* cur = head;
while (cur->next != NULL) {
cur = cur->next;
}
cur->next = new ListNode(val);
}
void LinkedList::deleteNode(int val) {
ListNode* cur = head;
while (cur->next != NULL) {
if (cur->next->val == val) {
ListNode* tmp = cur->next;
cur->next = cur->next->next;
delete tmp;
return;
}
cur = cur->next;
}
}
void LinkedList::printList() {
ListNode* cur = head->next;
while (cur != NULL) {
cout << cur->val << " ";
cur = cur->next;
}
}
```
以上就是关于c++文件读取和写入以及链表的实现方法。