两个list相加

本文介绍如何在C++中实现两个list相加。强调了处理进位问题以及避免使用悬空指针的注意事项,通过新建指针确保内存管理正确。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

150题 2.5

ListNode* AddList(ListNode* root1, ListNode* root2,int& carry){
	if (root1==NULL && root2==NULL)
		return NULL;

	ListNode* result = AddList(root1->next,root2->next,carry);
	ListNode* temp = NULL;
	temp = new ListNode(0);
	temp->val = (root1->val+root2->val+carry)%10;
	carry = (root1->val+root2->val+carry)/10;
	temp->next = result;
	return temp;
}

ListNode* PadList(ListNode* root,int length){
	if (length==0)
		return root;

	ListNode* temp = new ListNode(0);
	temp->next = root;
	return PadList(temp,length-1);
}

ListNode* AddList(ListNode* root1, ListNode* root2){
	if (root1==NULL && root2==NULL)
		return NULL;
	if (root1==NULL)
		return root2;
	if (root2 == NULL)
		return root1;

	int len1=0;
	ListNode* temp = root1;
	while(temp!= NULL){
		len1++;
		temp = temp->next;
	}
	int len2=0;
	temp = root2;
	while(temp!= NULL){
		len2++;
		temp = temp->next;
	}
	int carry = 0;
	ListNode* result;
	if (len1<len2){
		temp=PadList(root1,len2-len1);
		result=AddList(temp,root2,carry);
	}
	else{
		temp=PadList(root2,len1-len2);
		result=AddList(root1,temp,carry);
	}
	if (carry == 1){
		ListNode* last= new ListNode(1);
		last->next = result;
		result = last;
	}
	return result;
	
}

1. 本来的想法是两个数都有的部分用一个函数处理,只有一个数的在用另一个函数处理………………
    把短的数用pad函数全部填上0,这样两个list的长度就一样了

2. 不要忘了,如果最后carry为1,要再多添加一个处理!!

3. new啊,new,又犯了错误,没有new,直接用了dangling指针。 另外new出来的指针返回是没有问题的,和上一篇c++指针测试里面的例子不同。





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值