两个list相加

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

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 =
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值