如何递归反向单链表

时间:2019-04-10 20:20:50

标签: python

以递归方式将节点的顺序从当前递归颠倒到末端。         拆分当前节点及其后继节点(剩余节点)。         递归地反转后继节点,并使其尾部指向当前节点。         使当前节点指向无。

class _Node:

    def __init__(self, element, next=None):
        self._element = element
        self._next = next

    def element(self):
        return self._element

    def next(self):
        return self._next

    def set_element(self, element):
        self._element = element

    def set_next(self, next):
        self._next = next

def __init__(self, head=None):
    """Create a singly linked list that contains only head, not size"""
    self._head = head


def __str__(self):
    """Returns the string representation and the number of elements"""
    count = 0
    p = self._head
    rep = f''
    while p:
        rep += str(p.element()) + ' -> '
        p = p.next()
        count += 1
    rep += f'None: {count} element(s)'
    return rep

def reverse_recursively(self, current):

    if current is None:
        return current
    if current._next is None:
        return current
    successors = self.reverse_recursively(current.next())
    current._next._next = current
    current._next = None

我期望反转的输出,但实际输出只是第一个节点,而没有。

1 个答案:

答案 0 :(得分:0)

该算法确实是不正确的,因为它不会重定向self._head属性以指向最后一个节点。

实际上,您不需要将参数传递给此方法。而是在递归到链接列表的末尾时逐渐移动self._head

这是代码的外观:

def reverse_recursively(self):
    current = self._head
    if current is None:
        return
    successor = current._next
    if successor is None:
        return
    current._next = None
    self._head = successor
    self.reverse_recursively()
    successor._next = current