Python单向链表中间节点

360影视 2025-01-16 21:22 2

摘要:def find_middle_node_value(path, n, nodes):# 构建链表node_dict = {}for node in nodes:addr, value, next_addr = nodenode_dict[addr] = (v

def find_middle_node_value(path, n, nodes):# 构建链表node_dict = {}for node in nodes:addr, value, next_addr = nodenode_dict[addr] = (value, next_addr)# 遍历链表,收集节点值values = current_addr = pathwhile current_addr != '-1':value, next_addr = node_dict[current_addr]values.append(int(value)) # 将节点值转换为整数current_addr = next_addr# 找到中间节点值mid = len(values) // 2return values[mid]# 从标准输入读取数据if __name__ == "__main__":# 读取第一行:链表头节点地址和节点数first_line = input.strip.splitpath = first_line[0] # 链表头节点地址n = int(first_line[1]) # 节点数# 读取后续的节点信息nodes = for _ in range(n):node_info = input.strip.splitnodes.append(node_info) # 将节点信息添加到列表中# 调用函数并输出结果result = find_middle_node_value(path, n, nodes)print(result)

来源:小风课堂

相关推荐