链表表示的数字相加

题目

You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1’s digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.

EXAMPLE

Input: (3 –> 1 –> 5), (5 –> 9 –> 2)

Output: 8 –> 0 –> 8

译文:

你有两个由单链表表示的数。每个结点代表其中的一位数字。数字的存储是逆序的, 也就是说个位位于链表的表头。写一函数使这两个数相加并返回结果,结果也由链表表示。

例子:(3 –> 1 –> 5), (5 –> 9 –> 2)

输入:8 –> 0 –> 8

思路:

时间上思路与合并两个有序单链表一样,

从低位开始,逐位开始相加,

/*
考虑情况比较多,
1.有空链表
2.两个链表长度不一样
3.有进位
*/
linKNode* addList(LinkNode * listOne, LinkNode * listTwo)
{
	int num;
	LinkNode * newList;  //结果放在新链表中
	newList=NULL;
	LinkNode *temP;
	int flag=0;
	if(NULL==listOne,NULL==listTwo)
	{
		return NULL;
	}
	while(listOne!=NULL&&listTwo!=NULL)//依位相加
	{
			num=listOne->a+listTwo->a+flag;
		flag=num/10;
		num=num%10;
		if(NULL==newList)
		{
			newList=new LinkNode();
			newList->a=num;
			temP=newList;
		}
		else
		{
			temP->next=new LinkNode();
			temP->next->a=num;
			temP=temP->next;
		}
		listOne=listOne->next;
		listTwo=listTwo->next;
		
	}

	while(listOne!=NULL)  //链表长度不一致,listOne
	{
		temP->next=new LinkNode();
		temP=temP->next;
		num=listOne->a+flag;
		flag=num/10;
		num=num%10;
		temP->a=num;
		listOne=listOne->next;
	}

	while(listTwo!=NULL)
	{
		temP->next=new LinkNode();
		temP=temP->next;
		num=listTwo->a+flag;
		flag=num/10;
		num=num%10;
		temP->a=num;
		listTwo=listTwo->next;
	}
	if(flag>0)  //最后位有进位
	{
		temP->next=new LinkNode();
		temP=temP->next;
		temP->a=flag;

	}
	temP->next=NULL;
	cout<<"result :"<<endl;
	
	return newList;

}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值