今天在写一道关于链表的题的时候,发现在调用函数时传入的指针实参在进入函数后,函数的形参是实参的一个副本,子函数执行完毕,形参就会消亡,并不会改变实参的值
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
void print(ListNode *head){
ListNode *p=head;
while(p!=NULL){
cout<<p->val<<endl;
p=p->next;
}
return ;
}
//将链表反转
void reverse(ListNode *head){
ListNode *pre=NULL,*nex=NULL,*p=NULL;
p=head;
while(p!=NULL){
nex=p->next;
p->next=pre;
pre=p;
p=nex;
}
cout<<"-------"<<endl;
//将head重新指向反转后的头指针
head=pre;
cout<<head<<endl;
cout<<"-------"<<endl;
return ;
}
int main()
{
// freopen(".../.txt","w",stdout);
// freopen(".../.txt","r",stdin);
ios::sync_with_stdio(false);
ListNode *head1=NULL,*head2=NULL,*pre=NULL;
int n,i;
cin>>n;
//头插法建立链表
for(i=0;i<n;i++){
int k;
cin>>k;
ListNode *nnew=new ListNode(k);
if(i==0)
head1=pre=nnew;
else{
pre->next=nnew;
pre=nnew;
}
}
cout<<head1<<endl;
reverse(head1);
cout<<head1<<endl;
return 0;
}
发现在reverse函数中试图改变head1的指向,但是在主函数中head1并没有变化