Python iterative and recursive


  • 0

    Recursive:

    class Solution(object):
        def reverseList(self, head):
            def recursive(node):
                if not node:
                    return None
                tmp = recursive(node.next)
                if not tmp:
                    node.next = None
                    return [node, node]
                tmp[1].next = node
                node.next = None
                return [tmp[0], node]
            if not head:
                return head
            return recursive(head)[0]
    

    iterative:

    class Solution(object):
        def reverseList(self, head):
            ans = ListNode(-1)
            tmp = None
            while head:
                next = head.next
                ans.next = head
                ans.next.next = tmp
                tmp = head
                head = next
            return ans.next
    

Log in to reply
 

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