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

前端 未结 8 840
我寻月下人不归
我寻月下人不归 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:22
    def reverse_list(self,node):
         if node is None:
             return //list is empty
         elif node.next is None:
            self.head = node // changing the head to last node after reversal
            return
         else:
            reverse_list(node.next) //call the function recursively until the end of the list
            node.next.next = node //reverse the link
            node.next = None
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
提交回复
热议问题