您的位置:首页 > 其它

用链表模拟大整数加法运算

2014-04-10 22:52 381 查看
例如:9>9>9>NULL + 1>NULL =>

1>0>0>0>NULL

肯定是使用递归啦,不然没办法解决进位+1问题,因为这时候要让前面的节点加1,而我们的单链表是永远指向前的。

此外对于999+1=1000,新得到的值的位数(4位)比原来的两个值(1个1位,1个3位)都多,所以我们将表头的值设置为0,如果多出一位来,就暂时存放到表头。递归结束后,如果表头为1,就在新的链表外再加一个新的表头。

//head1 length > head2, so M > N

public static int Add(Link head1, Link head2, ref Link newHead, int M, int N)

{

// goto the end

if (head1 == null)

return 0;

int temp = 0;

int result = 0;

newHead = new Link(null, 0);

if (M > N)

{

result = Add(head1.Next, head2, ref newHead.Next, M - 1, N);

temp = head1.Data + result;

newHead.Data = temp % 10;

return temp >= 10

}

else // M == N

{

result = Add(head1.Next, head2.Next, ref newHead.Next, M - 1, N - 1);

temp = head1.Data + head2.Data + +result;

newHead.Data = temp % 10;

return temp >= 10

}

}

这里假设head1比head2长,而且M、N分别是head1和head2的长度。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: