/// <summary> /// Merge two sorted linked lists and return it as a new list. /// The new list should be made by splicing together the nodes of the first two lists. /// Ex: /// Input: 1->2->4, 1->3->4 /// </summary> /// <param name="l1"></param> /// <param name="l2"></param> /// <returns></returns> public static LeetCodeListNode MergeTwoLists(LeetCodeListNode l1, LeetCodeListNode l2) { LeetCodeListNode curr = null, head = null, next = null;// = new ListNode(); while (l1 != null || l2 != null) { if (l1?.val > l2?.val) { next = new LeetCodeListNode(l1.val); l1 = l1.next; } else { next = new LeetCodeListNode(l2.val); l2 = l2.next; } if (head == null) { head = next; curr = next; } else { curr.next = next; curr = curr.next; } } return(l1); }
/// <summary> /// You are given two non-empty linked lists representing two /// non-negative integers.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. /// You may assume the two numbers do not contain any leading zero, /// except the number 0 itself. /// /// Example: /// Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) /// Output: 7 -> 0 -> 8 /// Explanation: 342 + 465 = 807. /// </summary> /// <param name="l1"></param> /// <param name="l2"></param> /// <returns></returns> public static LeetCodeListNode AddTwoNumbers(LeetCodeListNode l1, LeetCodeListNode l2) { int carryOver = 0; var sum = l1.val + l2.val; if (sum > 9) { carryOver++; sum %= 10; } LeetCodeListNode head = new LeetCodeListNode(sum); AddTwoNumbers(l1?.next, l2?.next, carryOver, head); return(head); }
private static void AddTwoNumbers(LeetCodeListNode l1, LeetCodeListNode l2, int carry, LeetCodeListNode prevNode) { if (l2 == null && l1 == null && carry == 0) { return; } var sum = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + carry; if (sum > 9) { carry = 1; sum %= 10; } else { carry = 0; } var next = new LeetCodeListNode(sum); prevNode.next = next; AddTwoNumbers(l1?.next, l2?.next, carry, next); }