Add Two Numbers II
Description
You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first 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.
Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
Example:
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 8 -> 0 -> 7
Solution(javascript)
function ListNode(val) {
this.val = val
this.next = null
}
const addTwoNumbers = (l1, l2) => {
const getStack = (head) => {
let current = head
const stack = []
while (current) {
stack.push(current)
current = current.next
}
return stack
}
const stack1 = getStack(l1)
const stack2 = getStack(l2)
let current = null
let digit = 0
while (stack1.length > 0 || stack2.length > 0) {
const node1 = stack1.pop()
const node2 = stack2.pop()
const num1 = node1 ? node1.val : 0
const num2 = node2 ? node2.val : 0
let value = num1 + num2 + digit
if (value >= 10) {
value -= 10
digit = 1
} else {
digit = 0
}
const node = new ListNode(value)
node.next = current
current = node
}
if (digit === 1) {
const node = new ListNode(1)
node.next = current
current = node
}
return current
}