给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 输出:7 -> 0 -> 8 原因:342 + 465 = 807
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode AddTwoNumbers(ListNode l1, ListNode l2)
{
ListNode a = l1, b = l2;
int l1Length = 0, l2Length = 0;
while (l1 != null)
{
l1Length++;
l1 = l1.next;
}
while (l2 != null)
{
l2Length++;
l2 = l2.next;
}
if(l1Length > l2Length)
{
//交换l1和l2的表头
ListNode temp = a;
a = b;
b = temp;
}
l1 = a;
l2 = b;
while (l1 != null)
{
int val = l1.val + l2.val;
int jinwei = 0;
if (val >= 10)
{
jinwei = val / 10;
val = val % 10;
}
l2.val = val;
ListNode temp = l2;
digui(temp, jinwei);
l2 = l2.next;
l1 = l1.next;
}
return b;
}
public void digui(ListNode temp, int jw)
{
if (temp.next == null && jw == 0)
{
return;
}
if (temp.next == null && jw != 0)
{
ListNode last = new ListNode(jw);
temp.next = last;
return;
}
int val = temp.next.val + jw;
if (val >= 10)
{
jw = val / 10;
val = val % 10;
}
else
{
jw = 0;
}
temp = temp.next;
temp.val = val;
digui(temp, jw);
}
}