更改链表(节点链)中最后找到的目标值

时间:2018-06-30 04:32:49

标签: python python-3.6

我试图弄清楚如何将链表中最后找到的目标值更改为替换值。例如,如果您有一个链接列表,例如;

[1,'next'],[2,'next'],[3,next'],[2,none]

我该如何只替换最后两个,而不是全部或第一个?这是我目前拥有的代码;

walker = node_chain
if node_chain is None:
    return None
elif walker['data'] == target_val and walker['next'] is None:
    walker = node.set_data(walker, replacement_val)
    return walker
else:
    while walker['next'] is not None:
        if walker['data'] == target_val:
            node_chain = node.set_data(walker, replacement_val)
            return node_chain
        walker = node.get_next(walker)
        if walker['next'] is None and walker['data'] == target_val:
            walker = node.set_data(walker, replacement_val)
            return walker

因此在给定的代码中,如果目标值为2,替换值为4,它将返回

[1,'next'],[4,'next'],[3,next'],[2,none]

而不是我想返回的东西;

[1,'next'],[2,'next'],[3,next'],[4,none]

谢谢你。

1 个答案:

答案 0 :(得分:0)

walker = node_chain
target_node = None
if node_chain is None:
    return None
else:
    while walker is not None:
        if walker['data'] == target_val:
            target_node = walker
        walker = node.get_next(walker)
    if target_node != None
        node_chain = node.set_data(target_node, replacement_val)

您应该执行以下操作。我不确定这是否行得通,因为我没有您的其他功能,但这应该可以使您大致了解