题目描述:给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)输出:7 -> 0 -> 8原因:342 + 465 = 807
代码实现:
import (
"fmt"
"strconv"
)
type ListNode struct {
Val int
Next *ListNode
}
func formatList(arr []int) *ListNode {
head := ListNode{0, nil}
current := &head
for _,v := range arr[:] {
next := new(ListNode)
next.Val = v
current.Next = next
current = next
}
return head.Next
}
func printLinkList(head *ListNode) {
fmt.Println("Start Print LinkList")
current := head
for current != nil {
fmt.Println(strconv.Itoa(current.Val))
current = current.Next
}
}
func main() {
var a1 = []int{2,4,3}
var a2 = []int{5,6,4}
l1 := formatList(a1[:])
l2 := formatList(a2[:])
newl := addTwoNumbers(l1, l2)
printLinkList(newl)
}
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
var head ListNode
current := &head
remain := 0
for l1 != nil || l2 != nil || remain > 0 {
sum := remain
if l1 != nil {
sum += l1.Val
l1 = l1.Next
}
if l2 != nil {
sum += l2.Val
l2 = l2.Next
}
next := new(ListNode)
next.Val = sum%10
current.Next = next
current = next
remain = sum/10
}
return head.Next
}