2015-04-03 173 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); 

}