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 contains 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.
Java:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode res = new ListNode(-1);
ListNode cur = res;
int carry = 0;
while (l1 != null || l2 != null) {
carry = carry + (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val);
l1 = l1 == null ? null : l1.next;
l2 = l2 == null ? null : l2.next;
cur.next = new ListNode(carry % 10);
cur = cur.next;
carry /= 10;
}
if (carry != 0) {
cur.next = new ListNode(carry);
}
return res.next;
}
}
Python:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
carry = 0
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if l1 is None and l2 is None:
return None if self.carry == 0 else ListNode(self.carry)
else:
self.carry += (0 if l1 is None else l1.val) + (0 if l2 is None else l2.val)
res = ListNode(self.carry % 10)
self.carry //= 10
res.next = self.addTwoNumbers(None if l1 is None else l1.next, None if l2 is None else l2.next)
return res
Go:
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
var res *ListNode = new(ListNode) // var res *ListNode = &ListNode{0, nil}
cur := res
carry := 0
for l1 != nil || l2 != nil || carry != 0 {
if l1 != nil {
carry += l1.Val
l1 = l1.Next
}
if l2 != nil {
carry += l2.Val
l2 = l2.Next
}
cur.Next = new(ListNode)
cur = cur.Next
cur.Val = carry % 10
carry /= 10
}
return res.Next
}