简体   繁体   English

为什么在这个实现中递归比迭代快? (Python 反转链表)

[英]Why is recursion faster than iteration in this implementation? (Python Reverse a Linked List)

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.我正在使用 leetcode,所以我的迭代版本击败了所有 python3 提交的 27.7%,而我的递归版本击败了 95.97% 的解决方案。 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)

I made a few performance tests and the two functions are very close to each other.我做了一些性能测试,这两个功能非常接近。 This could make the differences fall in the error margins and give the impression that the recursive version is faster.这可能会使差异下降到误差范围内,并给人以递归版本更快的印象。

You can make sure that the iterative version is faster by reducing the number of assignments:您可以通过减少分配数量来确保迭代版本更快:

def reverseList1( head: ListNode) -> ListNode:            
    prev = None      
    while head:
        prev,head.next,head = head,prev,head.next                  
    return prev

Even if you do the same thing in the recursive function:即使你在递归函数中做同样的事情:

def reverseList2(head: ListNode, prev = None) -> ListNode:
    if not head: return prev
    prev,head.next,head = head,prev,head.next
    return reverseList2(head, prev)

EDIT After running the performance tests several times, the performance differences turn out to be insignificant.编辑多次运行性能测试后,性能差异变得微不足道。 The iterative and recursive versions sometimes perform faster or not on each test run.迭代和递归版本有时在每次测试运行时执行得更快或更快。 This would mean that the speed scores are meaningless given that all versions perform identically given the margin of error.这意味着速度分数毫无意义,因为所有版本在误差范围内都具有相同的性能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM