删除所有节点值由 Python 在单向链表中'x'


def dele(node,target):
if not node:
return
if node.val == target:
node.next = node.next.next
node.next = None
dele(node.next,target)
return node

此代码不起作用。谁能告诉我我应该在递归规则上更改什么?谢谢!

请更具体地说明您看到的问题。您看到的错误/消息/结果是什么? 是否抛出错误或结果不是您所期望的?

有很多因素可能导致它无法正常工作。首先,我认为您不需要node.next = node.next.next行,因为无论如何您都将node.next设置为"无"。 您还需要存储某种临时节点,以允许您跟踪上一个节点,因为如果您删除其next节点,则需要修改其next字段。

我还没有测试过,但你可以尝试这样的东西:

def dele(node,target, prev):
if not node:
return
if node.val == target:
# set the previous node's next field to the current node's next field so that we skip over the current node (which we're removing) when iteraitng over the list
prev.next = node.next
# set current node to None
node = None
# continue to next node, passing in the node preceding this node (since we're deleting this node, the node before it will also be the node before the next item in the list)
dele(node.next,target, prev)
else:
# keep running on the next node, but pass the current one as previous, as we don't delete it
dele(node.next, target, node)
return node

相关内容

  • 没有找到相关文章

最新更新