![](/img/trans.png)
[英]How can I insert a node in a singly linked list using recursion given: 1. a pointer to the head node 2. the index to insert the new node
[英]How can I edit a pointer to a list node from a function in a recursion?
直到現在,我一直在編寫一個相當復雜的程序。 無論如何,我應該編寫一個操作結構列表的函數。 我試圖讓這個問題盡可能簡單,所以我寫下了一段非常簡單的代碼供參考。
事情是這樣的:首先我從另一個函數調用testf
,為它提供有效current
以及值為0的i
。這意味着testf在開始訪問其余代碼之前會調用自己大約100次。 這是所有生成的testf
實例開始得到解決的時候。
void testf(listnode *current, int *i) {
wordwagon *current2;
current2 = current;
if (*i < 100) {
*i = *i + 1;
current2 = current2->next;
testf(current2, i);
}
current = current->next;
return;
}
如果,假設我有足夠的連接列表節點,那么current = current->next;
“最后”testf函數訪問和編輯調用者的current2
值(這是該函數的current
)的正確方法,還是我可怕的錯誤? 如果我是,從被調用函數內部更改調用函數的變量的方法是什么,並確保它們不會在被調用函數返回后立即消失? 我發現很難掌握指針的工作原理。
我很可能遺漏了重要信息,或者我沒有清楚地問我的問題。 如果是這種情況請通知我,以便我可以根據您的需要進行編輯。
提前致謝。
您可以將指針傳遞給函數中的指針,並將其解析以獲取listnode指針,這是代碼在此之后的樣子(未經過編譯測試):
void testf(listnode **current, int *i) { // accept pointer to listnode pointer
wordwagon *current2;
current2 = *current; // retreive pointer value by dereferece
if (*i < 100) {
*i = *i + 1;
current2 = current2->next;
testf(¤t2, i); // recursively call by reference to the pointer
}
*current = (*current)->next; /* change the current pointer next pointer, CORRECTED as suggested by Azure */
return;
}
這是學習指針的非常好的文章列表:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.