Add Two Numbers

You are given two linked lists representing two non-negative numbers. 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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
class ListNode(var value: Int, var next: ListNode = null) {
  def +(that: ListNode): ListNode = {
    if (that == null) this
    else {
      val sum = this.value + that.value
      var next = new ListNode(sum / 10) + this.next + that.next
      if (next.value == 0 && next.next == null) next = null
      new ListNode(sum % 10, next)
    }
  }
}

/**
  * wrapper function
  * @param l1
  * @param l2
  * @return
  */
def addTwoNumbers(l1: ListNode, l2: ListNode): ListNode = {
  if (l1 != null && l2 != null) l1 + l2
  else if (l1 == null) l2
  else l1
}

/**
  * utility function
  * @param nums
  * @return
  */
def createLinkedList(nums: Array[Int]): ListNode = {
  nums
    .map(num => new ListNode(num))
    .foldRight[ListNode](null)((l: ListNode, r: ListNode) => {
    l.next = r; l
  })
}

/**
  * utility function
  * @param n
  */
def printLinkedList(n: ListNode): Unit = {
  var head = n
  while (head != null) {
    println(head.value)
    head = head.next
  }
}

var n1 = createLinkedList(Array(0))
var n2 = createLinkedList(Array(1))

printLinkedList(addTwoNumbers(n1, n2))

Last updated