您可以使用以下代码来实现一个读取文件并返回链表的函数:

class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

def readFile(filename):
    head = None
    current = None

    with open(filename, 'r') as file:
        for line in file:
            data = line.strip()
            node = Node(data)

            if head is None:
                head = node
                current = node
            else:
                current.next = node
                current = node

    return head

这个函数使用'with open'语句打开文件并逐行读取文件内容。每一行都被创建为一个新的节点,并连接到链表中。如果链表为空,则将新节点设置为链表的头节点和当前节点。否则,将新节点连接到当前节点的下一个节点,并更新当前节点为新节点。

最后,函数返回链表的头节点。

请注意,上述代码假设文件中的每一行都是有效的数据,并且数据已经过处理,例如去除了空格或换行符。如果您的文件格式不同,您可能需要进行适当的修改。


原文地址: https://www.cveoy.top/t/topic/pioj 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录