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

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

提交回复
热议问题