花了一个星期理解了这段代码,add_two_numbers
public static void calculateSum(ListNode tresult, ref int carry, int sum)
{if (sum >= 10)
{
carry = 1;
tresult.next = new ListNode(sum - 10);
}
else
{
carry = 0;
tresult.next = new ListNode(sum);
}
}
public static ListNode AddTwoNumbers(ListNode l1, ListNode l2)
{
ListNode tl1 = l1, tl2 = l2;
ListNode result = new ListNode(0);
ListNode tresult = result;
int carry = 0;
// both ListNode 1 and ListNode 2 have values
while (tl1 != null && tl2 != null)
{
calculateSum(tresult, ref carry, tl1.val + tl2.val + carry);
tl1 = tl1.next;
tl2 = tl2.next;
tresult = tresult.next;
}
// Debug.Assert(!(tl1 != null && tl2 != null), "tl1 and tl2 aren‘t null");
// either ListNode 1 or ListNode 2 has values (maybe) and don‘t forget carry.
while (tl1 != null)
{
calculateSum(tresult, ref carry, tl1.val + carry);
tl1 = tl1.next;
tresult = tresult.next;
}
while (tl2 != null)
{
calculateSum(tresult, ref carry, tl2.val + carry);
tl2 = tl2.next;
tresult = tresult.next;
}
// at this time, ListNode 1 and ListNode 2 should be null, however, carry could be null or not
// Debug.Assert(tl1 == null && tl2 == null, "calculation doesn‘t finish");
if (carry == 1) tresult.next = new ListNode(1);
// neither ListNode 1 nor ListNode 2 have values
return result.next;
}
}
public class ListNode
{
public int val;
public ListNode next;
public ListNode(int x) { val = x; }
}