[英]How to pass head from main to addNode function ? (LinkedList implementation via struct)
在下面給出的代碼中,我將頭指針從主要功能傳遞到addNode函數,這樣我保留了頭指針的位置(也將其傳遞給其他與LinkedList相關的函數以執行其他操作),但是下面的代碼無法正常工作,每次調用函數addNode時,都會得到Head node Created
,是否沒有正確將指針傳遞給addNode? 我如何實現將頭指針保留到列表並將其從main()
發送到addNode函數的目標?
using namespace std;
struct stud {
string stud_name;
string stud_roll:
stud *next_node;
};
void addNode(stud* head);
int main()
{ stud *head = nullptr;
addNode(head);
addNode(head);
addNode(head);
addNode(head);
addNode(head);
}
void addNode(stud* head)
{
stud *new_node = new stud;
new_node->next_node = NULL;
if (head == NULL)
{
head = new_node;
cout << "Head node Created" << endl;
}
else
{
stud *temp_head = NULL;
temp_head = head;
while (temp_head->next_node != NULL)
{
temp_head = temp_head->next_node;
cout << "Moving temp pointer" << endl;
}
temp_head->next_node = new_node;
cout << "Body node created" << endl;
}
}
您在這里所做的是,將指針傳遞給函數並在函數中(在本地)分配它,並且您希望該局部指針可以在函數范圍之外訪問和重用。 你看到問題了嗎?
在功能范圍內分配通過的頭(在通過時復制)將影響功能范圍。 您可以做的是通過引用傳遞此指針。 因此,您的代碼將像這樣更改:
struct stud {
string stud_name;
string stud_roll;
stud *next_node;
};
void addNode(stud *&head);
int main()
{
stud *head = nullptr;
addNode(head);
addNode(head);
addNode(head);
addNode(head);
addNode(head);
}
void addNode(stud *&head)
{
stud *new_node = new stud;
new_node->next_node = NULL;
if (head == NULL)
{
head = new_node;
cout << "Head node Created" << endl;
}
else
{
stud *temp_head = NULL;
temp_head = head;
while (temp_head->next_node != NULL)
{
temp_head = temp_head->next_node;
cout << "Moving temp pointer" << endl;
}
temp_head->next_node = new_node;
cout << "Body node created" << endl;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.