例如:9>9>9>NULL + 1>NULL =>  1>0>0>0>NULL

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

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

 
  
  1. //head1 length > head2, so M > N 
  2. public static int Add(Link head1, Link head2, ref Link newHead, int M, int N) 
  3.     // goto the end 
  4.     if (head1 == null
  5.         return 0; 
  6.     int temp = 0; 
  7.     int result = 0; 
  8.     newHead = new Link(null, 0); 
  9.     if (M > N) 
  10.     { 
  11.         result = Add(head1.Next, head2, ref newHead.Next, M - 1, N); 
  12.         temp = head1.Data + result; 
  13.         newHead.Data = temp % 10; 
  14.         return temp >= 10 ? 1 : 0; 
  15.     } 
  16.     else // M == N 
  17.     { 
  18.         result = Add(head1.Next, head2.Next, ref newHead.Next, M - 1, N - 1); 
  19.         temp = head1.Data + head2.Data + +result; 
  20.         newHead.Data = temp % 10; 
  21.         return temp >= 10 ? 1 : 0; 
  22.     } 

这里假设head1比head2长,而且M、N分别是head1和head2的长度。

转自:http://www.cnblogs.com/Jax/archive/2009/12/11/1621504.html