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 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
/**
* 思路很简单同时遍历两个链表即可
**/
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
var result = new(ListNode)
result.Val = -1
var tmpre = result
var add = 0
for (l1 != nil || l2 != nil) {
var v1 = 0
var v2 = 0
if (l1 != nil){
v1 = l1.Val
}
if (l2 != nil){
v2 = l2.Val
}
var sum = v1 + v2 + add
if tmpre.Val == -1 {
tmpre.Val = sum % 10
}else {
var tmp = new(ListNode)
tmp.Val = sum % 10
tmpre.Next = tmp
tmpre = tmp
}
add = sum / 10
if (l1 != nil){
l1 = l1.Next
}
if (l2 != nil) {
l2 = l2.Next
}
}
if add > 0 {
var tmp = new(ListNode)
tmp.Val = add
tmpre.Next = tmp
}
return result
}