LeetCode题解-2
题目: Add Two Numbers
解答:
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
t := new(ListNode)
ct := t
var sum int
more := 0
for {
if l1 == nil && l2 == nil {
break
}
sum = 0
if l1 != nil {
sum += l1.Val
l1 = l1.Next
}
if l2 != nil {
sum += l2.Val
l2 = l2.Next
}
sum += more
t.Next = &ListNode{
Val:sum % 10,
Next:nil,
}
t = t.Next
more = sum / 10
}
if more > 0 {
t.Next = &ListNode{
Val:more,
Next:nil,
}
}
return ct.Next
}