求助:调用链表函数报错,求完整调用流程
两个数字相加完整代码调用
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
链表相加函数:
package main
import (
"container/list"
"fmt"
)
type ListNode struct {
Val int
Next *ListNode
}
func main() {
//创建一个list
l1 := list.New()
l1.PushBack(2)
l1.PushBack(4)
l1.PushBack(3)
l2 := list.New()
l2.PushBack(4)
l2.PushBack(3)
for e := l1.Front(); e != nil; e = e.Next() {
fmt.Println(e.Value)
}
for e := l2.Front(); e != nil; e = e.Next() {
fmt.Println(e.Value)
}
//调用addTwoNumbers函数
}
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
head := &ListNode{0, nil}
current := head
carry := 0
for l1 != nil || l2 != nil || carry > 0 {
sum := carry
if l1 != nil {
sum += l1.Val
l1 = l1.Next
}
if l2 != nil {
sum += l2.Val
l2 = l2.Next
}
carry = sum / 10
current.Next = new(ListNode)
current.Next.Val = sum % 10
current = current.Next
}
return head.Next
}
可以关注我的公众号 golang那点事,里面得算法专栏有这道题得实现源码,以及多种解题思路
源码链接