How can I write a recursive function to reverse a linked list?

前端 未结 8 838
我寻月下人不归
我寻月下人不归 2021-02-09 12:39

I am looking to do it with Python. And I don\'t want to just print it in reverse, but actually reverse the given nodes. I have seen it done in other languages but had trouble fi

8条回答
  •  不思量自难忘°
    2021-02-09 13:00

    def reverse (item, tail = None):
        next = item.next
        item.next = tail
        if next is None:
            return item
        else:
            return reverse(next, item)
    

    Using such a simple linked list implementation:

    class LinkedList:
        def __init__ (self, value, next = None):
            self.value = value
            self.next = next
        def __repr__ (self):
            return 'LinkedList({}, {})'.format(self.value, repr(self.next))
    

    Example:

    >>> a = LinkedList(1, LinkedList(2, LinkedList(3, LinkedList(4))))
    >>> a
    LinkedList(1, LinkedList(2, LinkedList(3, LinkedList(4, None))))
    >>> b = reverse(a)
    >>> b
    LinkedList(4, LinkedList(3, LinkedList(2, LinkedList(1, None))))
    >>> a # note that there is a new head pointer now
    LinkedList(1, None)
    

提交回复
热议问题