簡體   English   中英

遞歸調用后的代碼是否僅在達到基本情況時才執行?

[英]Does the code after the recursion call get executed only when the base case is reached?

我寫了一個遞歸來反轉一個鏈表:

def reverseList(self, head: ListNode) -> ListNode:

    #Base case
    if not head or not head.next:
        return head
    
    
    #Recurence relation
    second= head.next
    reverse = self.reverseList(second)
    second.next = head
    head.next = None
    
    return reverse

關於代碼的執行,我有一個簡單的問題,特別是對於遞歸關系。

我讀它的方式,遞歸關系的前兩行確保我們移動到並處理鏈表中的下一個節點。

但是,我的問題是,什么時候

second.next = head
head.next = None

被執行? 是否僅在達到基本情況時? 同時我們將每個部分完成的調用存儲在遞歸堆棧中? 這是正確的嗎?

如果您好奇代碼是如何執行的,只需插入一些打印語句。

def countDown(amount, depth = 0):
    if amount == 0:
        print("finished")
        return amount
    amount -= 1
    print("entering depth", depth + 1, "amount is", amount)
    amount = countDown(amount, depth + 1)
    print("exiting depth", depth, "amount is", amount)
    return amount

countDown(10)

output 精美地表明 function 調用被放入堆棧並在提前返回發生時彈出

entering depth 1 amount is 9
entering depth 2 amount is 8
entering depth 3 amount is 7
entering depth 4 amount is 6
entering depth 5 amount is 5
entering depth 6 amount is 4
entering depth 7 amount is 3
entering depth 8 amount is 2
entering depth 9 amount is 1
entering depth 10 amount is 0
finished
exiting depth 9 amount is 0
exiting depth 8 amount is 0
exiting depth 7 amount is 0
exiting depth 6 amount is 0
exiting depth 5 amount is 0
exiting depth 4 amount is 0
exiting depth 3 amount is 0
exiting depth 2 amount is 0
exiting depth 1 amount is 0
exiting depth 0 amount is 0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM