public static ListNode SumListsForwardRepresentation(ListNode headA, ListNode headB) { int headALength = GetLength(headA); int headBLength = GetLength(headB); Carry carry = new Carry(); ListNode result = new ListNode(); if (headALength == headBLength) { result = SumListsForwardRepresentation(headA, headB, carry); } else { if (headALength > headBLength) { headB = AppendZerosInFront(headB, Math.Abs(headALength - headBLength)); } else { headA = AppendZerosInFront(headA, Math.Abs(headALength - headBLength)); } result = SumListsForwardRepresentation(headA, headB, carry); } if (carry.val > 0) { ListNode carryNode = new ListNode(carry.val); carryNode.Next = result; return(carryNode); } return(result); }
private static ListNode SumListsForwardRepresentation(ListNode headA, ListNode headB, Carry carry) { if (headA == null || headB == null) { return(null); } ListNode next = SumListsForwardRepresentation(headA.Next, headB.Next, carry); int value = carry.val + headA.Data + headB.Data; ListNode result = new ListNode(); result.Data = value % 10; carry.val = value >= 10 ? 1 : 0; result.Next = next; return(result); }