请给我一个完整的可以读写文件并且可交互的链表代码
时间: 2023-04-09 15:00:51 浏览: 82
以下是一个完整的可以读写文件并且可交互的链表代码:
```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
last_node = self.head
while last_node.next:
last_node = last_node.next
last_node.next = new_node
def display(self):
current_node = self.head
while current_node:
print(current_node.data)
current_node = current_node.next
def read_from_file(self, filename):
with open(filename, 'r') as f:
for line in f:
self.append(line.strip())
def write_to_file(self, filename):
with open(filename, 'w') as f:
current_node = self.head
while current_node:
f.write(str(current_node.data) + '\n')
current_node = current_node.next
if __name__ == '__main__':
linked_list = LinkedList()
linked_list.append(1)
linked_list.append(2)
linked_list.append(3)
linked_list.display()
linked_list.write_to_file('linked_list.txt')
new_linked_list = LinkedList()
new_linked_list.read_from_file('linked_list.txt')
new_linked_list.display()
```
这个代码可以创建一个链表,可以将链表中的数据写入文件,也可以从文件中读取数据并创建一个新的链表。
阅读全文
相关推荐















