2015-04-03 92 views
1

该函数用于在节点尾部插入一个节点。这只是我们书中的一个实践问题,我很难解决。 data()和link()函数分别用于检索节点的信息和下一个指针。编译器在这行上给我一个错误:cursor-> set_link(i);在C++(walter/savitch)中插入一个链接列表末尾的节点

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

} 
+0

在循环结束时,'光标== NULL'。 – 0x499602D2 2015-04-03 20:25:46

回答

2

您有两个问题。

首先是这样的:

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) 

的第二个问题是,你的循环之后的变量cursorNULL。循环条件应该是例如cursor->link() != NULL

+0

非常感谢!我完全忘了第二件事,那就是NULL。再次感谢! – user3874530 2015-04-03 20:33:54

+0

我仍然收到“cursor - > set_link(i)”行出错。错误是智能感知:对象具有与成员函数不兼容的类型限定符 对象类型为:const main_savitch_5 :: node – user3874530 2015-04-04 19:49:52

+0

@ user3874530这是因为您将'cursor'声明为指向常量数据的指针,即数据你不能修改。为了能够在常量对象上调用成员函数,函数还需要标记为“const”。但是既然你调用了'set_link'(我假设修改了这个对象),把'cursor'指向一个常量对象是没有意义的。 – 2015-04-05 08:39:17

0

最后工作CODE:

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

}