文章目录
题目
代码(8.9 首刷自解)
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
l1 = reverse(l1)
l2 = reverse(l2)
var flag int
dummy := &ListNode{Val: -1, }
p := dummy
for l1 != nil && l2 != nil {
newHead := &ListNode{Val: (flag+l1.Val+l2.Val)%10}
p.Next = newHead
flag = (flag+l1.Val+l2.Val)/10
p = p.Next
l1 = l1.Next
l2 = l2.Next
}
for l1 != nil {
newHead := &ListNode{Val: (flag+l1.Val)%10}
p.Next = newHead
flag = (flag+l1.Val)/10
p = p.Next
l1 = l1.Next
}
for l2 != nil {
newHead := &ListNode{Val: (flag+l2.Val)%10}
p.Next = newHead
flag = (flag+l2.Val)/10
p = p.Next
l2 = l2.Next
}
if flag != 0 {
newHead := &ListNode{Val: 1, }
p.Next = newHead
p = p.Next
}
return reverse(dummy.Next)
}
func reverse(head *ListNode) *ListNode {
if head == nil || head.Next == nil {
return head
}
newHead := reverse(head.Next)
head.Next.Next = head
head.Next = nil
return newHead
}