github.com/qiuhoude/go-web@v0.0.0-20220223060959-ab545e78f20d/algorithm/leetcode/addTwoNumbers_test.go (about) 1 package leetcode 2 3 import "testing" 4 5 func TestAddTwoNumbers(t *testing.T) { 6 7 } 8 9 //https://leetcode-cn.com/problems/add-two-numbers 10 type ListNode struct { 11 Val int 12 Next *ListNode 13 } 14 15 // 两个数相加 16 func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode { 17 18 // 正常情况 19 // 2 -> 4 -> 3 20 // 5 -> 6 -> 4 21 // 7 -> 0 -> 8 22 23 // 长度不相等 24 // 4 -> 4 25 // 5 -> 6 -> 4 26 // 9 -> 0 -> 5 27 28 // 有个链表没有 29 // 30 // 5 -> 6 -> 4 31 // 5 -> 6 -> 4 32 dummyHead := &ListNode{} 33 cur := dummyHead 34 carry := 0 35 var n1, n2, sum int 36 for l1 != nil || l2 != nil { 37 if l1 != nil { 38 n1 = l1.Val 39 l1 = l1.Next 40 } 41 if l2 != nil { 42 n2 = l2.Val 43 l2 = l2.Next 44 } 45 sum = n1 + n2 + carry 46 cur.Next = &ListNode{Val: sum % 10} 47 cur = cur.Next 48 carry = sum / 10 49 n1 = 0 50 n2 = 0 51 sum = 0 52 } 53 if carry > 0 { 54 cur.Next = &ListNode{Val: carry} 55 } 56 return dummyHead.Next 57 }