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

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

    def reverse_ll_pass(self):
    
        temp = self.head
        if temp is None:
            return
    
        return self.reverse_ll_recursive(temp,past=None)
    
    def reverse_ll_recursive(self,curr,past):
    
        if curr is None:
            self.head = past
            return self.head
        else:
            future = curr.next
            curr.next = past
            past = curr
            curr = future 
            return self.reverse_ll_recursive(curr,past)  
    

提交回复
热议问题