请给我一个完整的可以读写文件的链表代码
时间: 2023-04-09 13:00:35 浏览: 55
以下是一个简单的可以读写文件的链表代码:
```python
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
return
current_node = self.head
while current_node.next is not None:
current_node = current_node.next
current_node.next = new_node
def display(self):
current_node = self.head
while current_node is not None:
print(current_node.data)
current_node = current_node.next
def write_to_file(self, file_name):
with open(file_name, 'w') as f:
current_node = self.head
while current_node is not None:
f.write(str(current_node.data) + '\n')
current_node = current_node.next
def read_from_file(self, file_name):
with open(file_name, 'r') as f:
for line in f:
self.append(line.strip())
# Example usage:
ll = LinkedList()
ll.append(1)
ll.append(2)
ll.append(3)
ll.write_to_file('data.txt')
ll2 = LinkedList()
ll2.read_from_file('data.txt')
ll2.display()
```
这个代码定义了一个 `Node` 类和一个 `LinkedList` 类,其中 `Node` 类表示链表中的一个节点,包含一个数据项和一个指向下一个节点的指针。`LinkedList` 类包含一个头节点,以及一些方法来操作链表,包括添加节点、显示链表、将链表写入文件和从文件中读取链表。在 `write_to_file` 方法中,我们使用 `with open` 语句打开文件,然后遍历链表并将每个节点的数据写入文件中。在 `read_from_file` 方法中,我们使用 `with open` 语句打开文件,然后遍历文件中的每一行,将每一行的数据添加到链表中。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)