簡體   English   中英

使用遞歸時對返回語句的混淆

[英]Confusion for return statements when using recursion

我正在使用遞歸在鏈表的末尾插入一個節點。 該代碼工作正常。 但是我對return語句有點困惑。

我的理解是一個接一個:

第一次返回將返回一個新的節點head == null ,該函數將完成-無需執行其他操作

第二個將返回在尾部末端創建的節點-無需執行其他操作

每次遞歸調用insertNodeAtTail時,最后一個都會將所有節點放在堆棧上。 當第二個返回稱為head.next == null 所有節點都將從堆棧中彈出,直到到達第一個為止。 有效地成為鏈接列表中的第一個節點(指向頭)。

我的理解正確嗎?

public Node insertNodeAtTail(Node head, int data) {
    if(head == null) {
    /* List is empty so just return the new node */
        Node node = new Node();
        node.data = data;
        node.next = null;
        return node;
    }
    else if (head.next == null) {
    /* We are at the end of the list so insert the new node */
        Node node = new Node();
        node.data = data;
        head.next = node;
        return head;
    }
    else {
    /* Travese the list by passing the next node in the list until next is NULL */
        insertNodeAtTail(head.next, data);
    }

    /* This will put all the head nodes on the stack and then pop them off at the end */ 
    return head;
 }

非常感謝您的任何建議,

只需這樣做

public Node insertNodeAtTail(Node head, int data) {
 if(head == null) {
    head = new Node(data);
 }
 else{
    head.next = insertNodeAtTail(head.next,data);
 }
 return head;
}

您只需將return放置在錯誤的位置,並返回相同的head元素即可。

else {
/* Travese the list by passing the next node in the list until next is NULL */
    return insertNodeAtTail(head.next, data);
}

我從頭寫這個請檢查。

是的,您的理解是正確的... :)

最后一次返回將導致問題,因為它將導致Head始終指向列表的倒數第二個節點。 您應該按照FallAndLearn的建議刪除它。 如果我錯了,請糾正我。

暫無
暫無

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

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