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

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

    Slight modification to @Rajat Bhatt implementation. Difference is below code can be executed as a separate function outside of linked list class.

    print '\n-- Initialize --'
    lst = LinkedList(10)    # 10 --> *
    print '\n-- Insert --'
    lst.append(20)          # 10 --> 20 --> *
    lst.append(30)          # 10 --> 20 --> 30 --> *
    lst.insertAt(15, pos=1) # 10 --> 15 --> 20 --> 30 --> *
    lst.insertAt(25, pos=3) # 10 --> 15 --> 20 --> 25 --> 30 --> *
    lst.insertAt(2)         # 2 --> 10 --> 15 --> 20 --> 25 --> 30 --> *
    lst.append(100)         # 2 --> 10 --> 15 --> 20 --> 25 --> 30 --> 100 --> *
    lst.append(500)         # 2 --> 10 --> 15 --> 20 --> 25 --> 30 --> 100 --> 500 --> *
    
    
    print lst
    # 2 --> 10 --> 15 --> 20 --> 25 --> 30 --> 100 --> 500 --> *
    
    print '\n-- Reverse using Recursion --'
    def revFunc(curr):
        if curr.next_node is None:
            lst.head = curr
            return None
    
        revFunc(curr.next_node)
        curr.next_node.next_node = curr
        curr.next_node = None
    
    revFunc(lst.head)
    
    print lst               
    # Head --> 500 --> 100 --> 30 --> 25 --> 20 --> 15 --> 10 --> 2 --> *
    

提交回复
热议问题