You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AddTwoNum
{
class AddTwoListNum
{
public LisNode AddTwoNum(LisNode l1,LisNode l2)
{
if (l1 == null)
{
return l2;
}
if (l2 == null)
{
return l1;
}
int len1 = 0;
int len2 = 0;
LisNode header = l1;
while(header!=null)
{
++len1;
header = header.next;
}
header = l2;
while(header!=null)
{
++len2;
header = header.next;
}
LisNode longer = len1 >= len2 ? l1 : l2;
LisNode shorter = len1 < len2 ? l1 : l2;
int num1=0;
int num2=0;
LisNode sum = null;
LisNode res = null;
while(shorter!=null)
{
num1 = longer.val + shorter.val + num2;
num2 = num1 / 10;
num1 -= num2 * 10;
if(sum==null)
{
sum = new LisNode(num1);
res = sum;
}
else
{
sum.next = new LisNode(num1);
sum = sum.next;
}
shorter = shorter.next;
longer = longer.next;
}
while(longer!=null)
{
num1 = longer.val + num2;
num2 = num1 / 10;
num1 -= num2 * 10;
sum.next = new LisNode(num1);
sum = sum.next;
longer = longer.next;
}
if(num2!=0)
{
sum.next = new LisNode(num2);
}
return sum;//相当于返回第一个头节点,或者说返回一个位置,剩余位置也都知道了
}
}
}