指针形参

今天在写一道关于链表的题的时候,发现在调用函数时传入的指针实参在进入函数后,函数的形参是实参的一个副本,子函数执行完毕,形参就会消亡,并不会改变实参的值

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并没有变化

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值