| 
 | 1 | +const LinkedList = require('./../util/LinkedList')  | 
 | 2 | +const printList = require('./../util/printList')  | 
 | 3 | + | 
 | 4 | +function sumLinkedListsForward(list1, list2) {  | 
 | 5 | +  if (!list1 && !list2) {  | 
 | 6 | +    return null  | 
 | 7 | +  }  | 
 | 8 | +  let length1 = length(list1)  | 
 | 9 | +  let length2 = length(list2)  | 
 | 10 | + | 
 | 11 | +  if (length1 > length2) {  | 
 | 12 | +    list2 = padList(list2, length1 - length2)  | 
 | 13 | +  } else if (length1 < length2) {  | 
 | 14 | +    list1 = padList(list1, length2 - length1)  | 
 | 15 | +  }  | 
 | 16 | + | 
 | 17 | +  const { head, nextDigitValue } = carryBase10(sumAndAppendNodes(list1, list2), 0)  | 
 | 18 | +  return nextDigitValue ? appendToStart(head, new LinkedList(nextDigitValue)) : head  | 
 | 19 | +}  | 
 | 20 | + | 
 | 21 | +function length(node) {  | 
 | 22 | +  let count = 0  | 
 | 23 | +  while (node) {  | 
 | 24 | +    count++  | 
 | 25 | +    node = node.next  | 
 | 26 | +  }  | 
 | 27 | +  return count  | 
 | 28 | +}  | 
 | 29 | + | 
 | 30 | +function padList(shortList, padding) {  | 
 | 31 | +  while (padding > 0) {  | 
 | 32 | +    shortList = appendToStart(shortList, new LinkedList(0))  | 
 | 33 | +    padding--  | 
 | 34 | +  }  | 
 | 35 | +  return shortList  | 
 | 36 | +}  | 
 | 37 | + | 
 | 38 | +function appendToStart(head, node) {  | 
 | 39 | +  node.next = head  | 
 | 40 | +  return node  | 
 | 41 | +}  | 
 | 42 | + | 
 | 43 | +function sumAndAppendNodes(node1, node2) {  | 
 | 44 | +  let value = (node1 ? node1.value : 0) + (node2 ? node2.value : 0)  | 
 | 45 | +  if (!node1.next && !node2.next) {  | 
 | 46 | +    return new LinkedList(value)  | 
 | 47 | +  }  | 
 | 48 | +  const {  | 
 | 49 | +    head,  | 
 | 50 | +    nextDigitValue  | 
 | 51 | +  } = carryBase10(sumAndAppendNodes(node1.next, node2.next), value)  | 
 | 52 | +  return appendToStart(head, new LinkedList(nextDigitValue))  | 
 | 53 | +}  | 
 | 54 | + | 
 | 55 | +function carryBase10(head, nextDigitValue) {  | 
 | 56 | +  if (head.value >= 10) {  | 
 | 57 | +    head.value = head.value % 10  | 
 | 58 | +    nextDigitValue += 1  | 
 | 59 | +  }  | 
 | 60 | +  return {  | 
 | 61 | +    head,  | 
 | 62 | +    nextDigitValue  | 
 | 63 | +  }  | 
 | 64 | +}  | 
 | 65 | + | 
 | 66 | +// Input: (6 -> 1 -> 7) + (2 -> 9 -> 5). this case refers to 617 + 295  | 
 | 67 | +// Output: 9 -> 1 -> 2. the answer refers to 912  | 
 | 68 | + | 
 | 69 | +var a = new LinkedList(6)  | 
 | 70 | +var b = new LinkedList(1)  | 
 | 71 | +var c = new LinkedList(7)  | 
 | 72 | + | 
 | 73 | +a.next = b  | 
 | 74 | +b.next = c  | 
 | 75 | + | 
 | 76 | +var d = new LinkedList(2)  | 
 | 77 | +var e = new LinkedList(9)  | 
 | 78 | +var f = new LinkedList(5)  | 
 | 79 | + | 
 | 80 | +d.next = e  | 
 | 81 | +e.next = f  | 
 | 82 | + | 
 | 83 | +printList(sumLinkedListsForward(a, d))  | 
0 commit comments