/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
if l1 == nil {
return l2
}
if l2 == nil {
return l1
}
sum := l1.Val + l2.Val
jw := sum/10
sum = sum%10
head := &ListNode{sum,nil}
tmp := head
val1 := 0
val2 := 0
l1 = l1.Next
l2 = l2.Next
for l1 != nil || l2 != nil || jw != 0 {
if l1 == nil {
val1 = 0
} else {
val1 = l1.Val
l1 = l1.Next
}
if l2 == nil {
val2 = 0
} else {
val2 = l2.Val
l2 = l2.Next
}
sum = val1 + val2 + jw
jw = sum/10
sum = sum%10
tmp.Next = &ListNode{sum,nil}
tmp = tmp.Next
}
return head
}
有疑问加站长微信联系(非本文作者)