using System;
internal class Test
{
static void Main()
{
ListNode list1 = new ListNode(9);
ListNode list2 = new ListNode(9,list1);
ListNode list3 = new ListNode(9,list2);
ListNode list4 = new ListNode(9,list3);
ListNode list5 = new ListNode(9,list4);
ListNode list6 = new ListNode(9,list5);
ListNode list7 = new ListNode(9,list6);
ListNode list8 = new ListNode(9);
ListNode list9 = new ListNode(9,list8);
ListNode list10 = new ListNode(9,list9);
ListNode list11 = new ListNode(9,list10);
ListNode result = AddTwoNumbers(list7, list11);
Test1(result);
}
public static void Test1(ListNode node)
{
if (node != null)
{
Console.WriteLine(node.val);
Test1(node.next);
}
}
public static ListNode AddTwoNumbers(ListNode l1, ListNode l2)
{
ListNode first = new ListNode();
ListNode last = new ListNode();
while (l1!=null && l2!=null)
{
//获得两链表对应位置相加的值
int temp = l1.val + l2.val + last.val;
//对相加值进行分离处理,小于10则直接将相加值给下一个结果节点
if (temp < 10)
{
if (first.next == null)
{
first.val = temp;
if (l1.next == null && l2.next == null) break; //防止创建一个多余的尾节点
first.next = last;
}
else
{
last.val = temp;
if (l1.next == null && l2.next == null) break; //防止创建一个多余的尾节点
last.next = new ListNode();
last = last.next;
}
}
//当相加值大于10时,则将相加值的个位作为前一个节点,将相加值的十位作为后一个节点
else
{
//先将相加值分成个位和十位
int geWei = temp % 10;
int shiWei = (temp - geWei) / 10;
//若是首个节点
if (first.next == null)
{
first.val = geWei;
first.next = last;
last.val = shiWei;
}
else
{
//分别赋予last和last.next值
last.val = geWei;
last.next = new ListNode();
last.next.val = shiWei;
last = last.next;
}
}
if (l1.next == null && l2.next!=null)
{
l2 = l2.next;
l1.val = 0;
continue;
}
if(l1.next!=null && l2.next == null)
{
l1 = l1.next;
l2.val = 0;
continue;
}
l1 = l1.next;
l2 = l2.next;
}
return first;
}
}
public class ListNode
{
public int val;
public ListNode next;
public ListNode(int val = 0, ListNode next = null)
{
this.val = val;
this.next = next;
}
}