Python iterative and recursive solution, both O(n) time complexity.


  • 0
    C
    # Iteratively
    def reverseList1(self, head):
        node = None
        while head:
            tmp = head.next
            head.next = node
            node = head
            head = tmp
        return node
     
    # Recursively    
    def reverseList(self, head):
        return self.helper(head, None)
        
    def helper(self, head, node):
        if not head:
            return node
        tmp = head.next
        head.next = node
        return self.helper(tmp, head)

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.