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

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

    Another way to do it with recursion:

    def reverse(head):
      # Empty list is always None
      if not head:
        return None
    
      # List of length 1 is already reversed
      if not head.get_next():
        return head
    
    
      next = head.get_next()
    
      head.set_next(None)
    
      rest = reverse(next)
    
      next.set_next(head)
    
      return rest
    

提交回复
热议问题