我正在使用遞歸在鏈表的末尾插入一個節點。代碼工作正常。但是我對迴歸聲明有點困惑。使用遞歸時混淆返回語句
通過一個去通過我的理解一個:
第一回會返回一個新的節點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;
}
非常感謝您的任何建議,在錯誤的地方
是的,你的理解是正確的。我不確定返回值的重點是什麼,它沒有被使用。 – Zarwan
@Zar每次添加東西時都可能檢索根節點,因爲始終會返回根節點。 – EvilTak
請注意,第一種情況('head == null')不會向列表中添加任何內容(也就是說,除非您將您的方法返回的節點分配給List的'head'成員 - 如果您不做到這一點,你的方法不適用於空列表) – Eran