-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