funcaddTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode { h := &ListNode{} for s := h; l1 != nil; l1 = l1.Next { s.Val = l1.Val if l1.Next != nil { s.Next = &ListNode{} } s = s.Next } k := 0 s, e := h, h for l2 != nil { s.Val += l2.Val + k k = 0 if s.Val >= 10 { s.Val -= 10 k = 1 } if s.Next == nil { s.Next = &ListNode{} } e = s s = s.Next l2 = l2.Next } for k != 0 && s != nil { s.Val += k k = 0 if s.Val >= 10 { s.Val -= 10 k = 1 } s = s.Next e = e.Next } if k != 0 { if s != nil { e.Next.Val += 1 } else { e.Next = &ListNode{Val: 1} } } for s != nil { if s.Val == 0 && s.Next == nil { e.Next = nil } s = s.Next e = e.Next } return h }
本地测试
package main
import"fmt"
type ListNode struct { Val int Next *ListNode }
funcprint(h *ListNode) { for h != nil { fmt.Print(h.Val) h = h.Next } fmt.Println() }