2014-12-04 88 views
-2

/*這很簡單,將節點添加到鏈接列表。我無法弄清楚爲什麼每次調用添加函數時頭指針都被設置爲null。 */ //節點的結構聲明 struct node int data; node * next; };將節點添加到C++中的鏈接列表中

node *head; 

//adding node to the head pointer 
void addnode(node* head,int d) 
{ 
node *temp = new node; 
temp->data =d; 
temp->next=NULL; 
node* tmp=head; 
if(tmp!=NULL) 
{ 
    cout<<"shal"; 
    while(tmp->next!=NULL) 
    tmp=tmp->next; 
    tmp->next=temp; 
} 
else 
{ 
    //cout<<temp->data; 
    head=temp; 
} 
    cout<<"dh"<<head->data; 
} 

//main function 
int main() 
{`enter code here` 
    head=NULL; 
//calling the add function 
    addnode(head,10); 
//head is being taking as null here 
    addnode(head,20); 
} 

/*輸出:dh10nulldh20null 請幫我瞭解哪裏出了問題。謝謝。*/

+0

你有一個全局'head'和一個參數'head'?好惡。停止使用全局變量來做一件事。 – crashmstr 2014-12-04 14:52:39

+0

您需要了解按值傳遞和按引用傳遞的行爲差異。 – Speed8ump 2014-12-04 15:15:09

回答

0

我想你沒有得到什麼指針。

void plus_one(int num) { 
    num += 1; 
} 

int main() { 
    int num = 42; 
    plus_one(num); 
    std::cout << num << std::endl; 
} 

顯然,num依然42.爲什麼呢?因爲在功能plus_one你通過複製num

當您致電addnode時,會發送head指針的副本。既然它是一個指針,你可以修改指針指向的內容,而不是指針本身。你所做的和我的例子一樣,試圖獲得43 ......如果你得到一份副本,這是不可能的。

您需要傳遞指針的地址,因此請調用您的函數:addnode(&head, 10);並將您的原型編寫爲:void addnode(node** head,int d)。你將不得不修改你的功能,以適應你的新node**

它爲什麼有效?因爲您修改了指向您的原始指針(指向您的結構)的指針的內容。