1. 题目
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.
Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
2. 结果
2.1 golang版
type ListNode struct {
Val int
Next *ListNode
}
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
temp := &ListNode{}
result := temp
p := l1
q := l2
carry := 0
for p != nil && q != nil {
temp.Next = &ListNode{}
temp.Next.Val = (carry + p.Val + q.Val) %10
carry = (carry + p.Val + q.Val) / 10
p = p.Next
q = q.Next
temp = temp.Next
}
for p != nil{
temp.Next =&ListNode{}
temp.Next.Val = (carry + p.Val ) %10
carry = (carry + p.Val ) / 10
p = p.Next
temp = temp.Next
}
for q != nil{
temp.Next =&ListNode{}
temp.Next.Val = (carry + q.Val ) %10
carry = (carry + q.Val ) / 10
q = q.Next
temp = temp.Next
}
if carry != 0{
temp.Next = &ListNode{}
temp.Next.Val = carry
}
return result.Next
}
3. 分析
本题目其实是两个链表合并的问题。
- 为了容易操作,我们先定义了result链表来表示新的结果链表,同时设置头指针。
- 进行链表相加的操作。在进行链表相加时,当一个链表为空时。不能用if直接进行链表后续的连接,
if q != nil{
temp.Next =&ListNode{}
temp.Next.Val = (carry + q.Val ) %10
temp.Next.Next= q.Next
}
因为,有可能存在1+99这种,会导致一直有进位相加,需要用for循环。
3.当两个链表都已经遍历到空时,需要注意如果最后有进位要把进位给加上。
网友评论