2016-09-27 57 views
1

我正在使用遞歸在鏈表的末尾插入一個節點。代碼工作正常。但是我對迴歸聲明有點困惑。使用遞歸時混淆返回語句

通過一個去通過我的理解一個:

第一回會返回一個新的節點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; 
} 

非常感謝您的任何建議,在錯誤的地方

+0

是的,你的理解是正確的。我不確定返回值的重點是什麼,它沒有被使用。 – Zarwan

+0

@Zar每次添加東西時都可能檢索根節點,因爲始終會返回根節點。 – EvilTak

+0

請注意,第一種情況('head == null')不會向列表中添加任何內容(也就是說,除非您將您的方法返回的節點分配給List的'head'成員 - 如果您不做到這一點,你的方法不適用於空列表) – Eran

回答

3

只要做到這一點

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

我在else語句中移動了返回頭,代碼工作正常。我知道它的工作原理。但仍然與head.next = insertNodeAtTail(head.next,data)相混淆;那個insertNodeAtTail會返回什麼? – ant2009

+1

它將在列表的末尾添加一個節點,並最終返回頭部。 – FallAndLearn

2

你只需把回報,同樣的頭元素。

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

我從頭寫這個請檢查。

+0

其實,我沒有嘗試過,並且函數崩潰了一個空異常。 – ant2009

1

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

1

末迴歸會產生問題,因爲它會導致團長總是指向列表的倒數第二個節點。您應該按照FallAndLearn的建議移除它。糾正我,如果我錯了。

+0

我在我的問題中編寫的原始代碼在我的測試用例中確實成功,所以它始終會在開始時返回第一個頭,因爲所有節點都會彈出堆棧,而最後一個彈出堆棧的將是第一個一。因此,頭將指向第一個節點。 – ant2009