# 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
```

{% tabs %}
{% tab title="Scala" %}

```scala
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))
```

{% endtab %}

{% tab title="Second Tab" %}

{% endtab %}
{% endtabs %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://blog.bernardw.com/problems/add-two-numbers.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
