[英]Inserting a node at the end of a linked list in c++ (walter/savitch)
此功能旨在在尾節點之后插入一個節點。 這只是我遇到的困難,是我們書中的一個實踐問題。 有data()和link()函數,分別用於檢索節點的信息和下一個指針。 編譯器在此行給我一個錯誤:cursor-> set_link(i);
void list_tail_insert(node* head_ptr, const node::value_type& entry)
{
assert (head_ptr != NULL);
const node *temp = head_ptr;
const node *cursor;
node *i = new node; // this is the new tail pointer
i->set_data(entry);
i->set_link(NULL);
if (!head_ptr) // if the linked list is empty
{
head_ptr = i; // the tail pointer is the new head pointer
}
for (cursor = head_ptr; cursor != NULL; cursor = cursor -> link())
{
cout << "Iterating to the tail pointer" << endl;
}
cursor->set_link(i);
}
你有兩個問題。
首先是這樣的:
if (!head_ptr) // if the linked list is empty
{
head_ptr = i; // the tail pointer is the new head pointer
}
在這里,您分配給head_ptr
變量,但是由於變量是通過value傳遞的 ,這意味着它們已被復制,因此您僅更改了變量的本地副本。 從調用者傳遞給函數的變量將不會更改。 為了使其正常工作,您必須通過引用傳遞頭指針:
void list_tail_insert(node*& head_ptr, const node::value_type& entry)
第二個問題是循環后變量cursor
將為NULL
。 循環條件應為例如cursor->link() != NULL
。
最終工作代碼:
void list_tail_insert(node* head_ptr, const node::value_type& entry)
{
assert (head_ptr != NULL);
node *cursor;
node *i = new node; // this is the new tail pointer
i->set_data(entry);
i->set_link(NULL);
if (!head_ptr) // if the linked list is empty
{
head_ptr = i; // the tail pointer is the new head pointer
}
for (cursor = head_ptr; (cursor -> link()) != NULL; cursor = cursor -> link())
{
cout << "Iterating to the tail pointer" << endl;
}
cursor->set_link(i);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.