2014-12-04 99 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**

它为什么有效?因为您修改了指向您的原始指针(指向您的结构)的指针的内容。