在c++中的链表末尾插入一个节点(walter/savitch)

Inserting a node at the end of a linked list in c++ (walter/savitch)

本文关键字:一个 c++ 节点 walter savitch 链表 插入      更新时间:2023-10-16

此函数用于在尾部节点后插入一个节点。这只是我们书中的一个练习题,我很难解决。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变量,但由于变量是通过值传递的,这意味着它们被复制,因此您只更改变量的本地副本。从调用方传递给函数的变量不会更改。要使其工作,您必须通过引用传递头指针

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);
}