我有一个节点需要通过Python中的递归来反转。我使用了以下代码:
class Node:
def __init__(self, value):
'''
Initiate a node
:param value: float | int | str
'''
self.value = value
self.nxt = None
def reverse(n):
"""
Reverse a given linked-node
:param n: Node
:return: None
"""
if n is None or n.nxt is None:
return
else:
rest = n.nxt
n.nxt = None
reverse(rest)
#reach the end of rest
current = rest
while current.nxt:
current = current.nxt
current.nxt = n
n = rest
这当然不起作用,因为更改n的值只是更改它的引用而不是实际节点,所以我得到的结果只是同一个节点,其next = None! 有什么帮助吗?!
答案 0 :(得分:0)
我做了一些调整,但是有效:
def reverse(n, prev=None):
""" Reverse a given linked-node
:param n: Node
:return: None"""
if n is None or n.nxt is None:
return n
rest = n.nxt
n.nxt = prev
return reverse(rest, n)