2014-02-21 32 views
0

我寫了這個功能:函數,鏈表。複製一個鏈表到另一個

void something(struct node* head1, struct node* head2) 
{ 
    statement 1 ....... 
    statement 2 ....... 
    so on......... 
    // Want to make list2 (head1) be the same as list1 (head1): 
    head2=head1 
} 

但是這並不能改變head2。它在函數中執行,但是一旦它回到主程序中,爲什麼?

+2

你怎麼稱呼「東西」功能? – 44kksharma

+1

如果您使用所用語言標記問題,您會得到更好的回覆。看起來就像代碼示例中的C一樣。 – sinoth

+0

如果這是C:你不能分配實際值,並期望它們會改變。你*可以*改變指向的值。因此,你不能改變指針'head1'或'head2',但你可以改變它們指向的結構。 – Evert

回答

0

看來你想要head1和head2都應該指向相同的鏈表,你的代碼的問題是你傳遞參數作爲調用的價值,這就是爲什麼它沒有反射出你需要傳遞的函數通過指針調用參數(參考)。 試試這個方法

struct Node 
{ 
int info; 
Node *next; 
} 

main{ 
Node * head1,*head2; 

// call like this 

something(&head1,&head2); 

} 

something(Node **temphead1, Node **temphead2){ 

//here you can use 

//(*temphead1) 

//and 

//(*temphead2) 

//to perform operation 

//for example you can display list item 

while((*temphead1)!=null){ 

printf("%d",(*temphead1)->info); 

(*temphead1)=(*temphead1)->next; 
} 

while((*temphead2)!=null){ 

printf("%d",(*temphead2)->info); 

(*temphead2)=(*temphead2)->next; 

} 
// below line will do what you were looking for 

(*temphead2)=(*temphead1); 

// now you can check head1 =head2 

}