I have solved the "reverse a linked list" problem with both iterative and recursively. The results were unexpected for me. I am using leetcode so my iterative version beat the 27.7% of all the python3 submissions where as my recursive version beat the 95.97% of the solutions. I know that it might be due to tail call optimization but i do not understand HOW it could be. Could someone clarify this?
Here is my code for both of the implementations:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#def reverseList(self, head: ListNode) -> ListNode:
#
# prev = None
#
# while head:
# headsNext = head.next
# head.next = prev
# prev = head
# head = headsNext
#
# head = prev
#
# return head
class Solution:
def reverseList(self, head: ListNode, prev = None) -> ListNode:
if not head:
return prev
headsNext = head.next
head.next = prev
prev = head
return self.reverseList(headsNext, prev)