-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 请帮我了解哪里出了问题。谢谢。*/
你有一个全局'head'和一个参数'head'?好恶。停止使用全局变量来做一件事。 – crashmstr 2014-12-04 14:52:39
您需要了解按值传递和按引用传递的行为差异。 – Speed8ump 2014-12-04 15:15:09