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

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

    After seeking to thoroughly understand how to reverse a linked list in python using both iterative and recursive methods, and working on an adequate refactoring, I coded this. Many links that I studied seemed slightly unclear or had unnecessary steps. If I have not arrived at the bare minimum / clear steps, I think these are at least close. I felt it best to not include the output, but it will run as is and produce output (python 2.7 and easy to modify for 3.x).

    class Node:
    def __init__(self,val):
        self.val = val
        self.next = None # the pointer initially points to nothing
    
    def traverse(self):
        # start from the head node
        node = self 
        while node != None:
            # access the node value
            out_string = 'val = %d, loc = %s, next = %s'
            print out_string % (node.val, node, node.next)
            # move on to the next node
            node = node.next 
    
    def reverse_iteratively(self):
        previous = None
        current = None
        head = self
    
        while head:
            # before reverse
            previous = current
            current = head
            head = head.next
            # reverse the link
            current.next = previous
    
    def reverse_recursively(self, node, pre=None):
        if node.next != None:
            self.reverse_recursively(node.next, pre=node)
        node.next = pre
    
    ### Operation Section
    node0 = Node(0)
    node1 = Node(7);  node0.next = node1
    node2 = Node(14); node1.next = node2
    node3 = Node(21); node2.next = node3
    node4 = Node(28); node3.next = node4
    node5 = Node(35); node4.next = node5
    node6 = Node(42); node5.next = node6
    node7 = Node(49); node6.next = node7
    node8 = Node(56); node7.next = node8
    node9 = Node(63); node8.next = node9
    
    print "Forward linked:"
    node0.traverse()
    node0.reverse_recursively(node0)
    print "Reverse linked:"
    node9.traverse()
    

提交回复
热议问题