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

前端 未结 8 835
我寻月下人不归
我寻月下人不归 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:23

    Very similar to poke's solution, but I prefer to have the base case first:

    def reverse(head, reversed=None):
        if head is None:
            return reversed
        new_head = head.next
        head.next = reversed
        new_reversed = head
        return reverse(new_head, new_reversed)
    

提交回复
热议问题