2017-05-27 26 views
-3

我的代碼是這樣的。 它顯示不能將節點轉換爲節點*。 請告訴我,我將如何使用傳遞引用來實現它。在鏈接列表中使用引用傳遞時遇到問題

#include <iostream> 
    using namespace std; 

    struct node 
    { 
     int data; 
     node* next; 
    }; 

node* insertfront(node &root, int v) 
{ 
node* temp = NULL; 
temp->data = v; 
temp->next = root; 
return temp; 
} 


int main() 
{ 
node* root; 
root = insertfront(root,5); 
return 0; 
} 
+1

提示:類型簽名也許應該是'無效insertfront(節點*根,INT V)'。 – melpomene

+0

遵循@ melpomene的建議改變'node * root = NULL;'並在'insertfront()'函數中處理這種情況。還要添加代碼爲該功能中添加的節點分配內存。 –

回答

1

你傳遞一個函數指針,你應該通過它像

root = insertfront(*root,5); 

,如果你想參考節點,或改變功能

node* insertfront(node *&root, int v) 

,如果你想引用指向節點的指針。 你也應該改變這個node* temp = NULL;,你應該在堆上使用內存分配,我的意思是使用new;

node *temp = new node; 

我想你的函數應該或多或少這個樣子的

node* insertfront(node *&root, int v) 
{ 
    node* temp = new node; 
    temp->data = v; 
    temp->next = root; 
    return temp; 
} 
+0

我在評論中提到了更多問題。要麼你在代碼中解決了所有的問題(用一個完整的例子),或者留下一個評論(就像已經完成的那樣)。這些答案只會導致OP的抱怨_「現在我有這個問題」_ ... –

相關問題