美文网首页
AddTwo Go写法

AddTwo Go写法

作者: FredricZhu | 来源:发表于2020-04-12 10:09 被阅读0次
    package main
    
    import (
        "fmt"
    )
    
    type ListNode struct {
        Val  int
        Next *ListNode
    }
    
    
    func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
        head := new(ListNode)
        cur := head
        p := l1
        q := l2
        carry := 0
        for p != nil || q != nil {
            var x = 0
            if p!=nil {
                x = p.Val
            }
    
            var y = 0
            if q != nil {
                y = q.Val
            }
            sum := carry + x + y
            carry = sum / 10
    
            cur.Next = &ListNode{Val: sum % 10}
    
            cur = cur.Next
            if p != nil {
                p = p.Next
            }
    
            if q != nil {
                q = q.Next
            }
        }
    
        if carry > 0 {
            cur.Next = &ListNode{Val: carry}
        }
        return head.Next
    }
    
    func main() {
        l1 := &ListNode{
            Val: 2,
            Next: &ListNode {
                Val: 4,
                Next: &ListNode {
                    Val: 3,
                },
            },
        }
    
        l2 := &ListNode{
            Val: 5,
            Next: &ListNode {
                Val: 6,
                Next: &ListNode {
                    Val: 4,
                },
            },
        }
    
        res := addTwoNumbers(l1, l2)
        head := res
        for head.Next != nil {
            fmt.Printf("%d\t", head.Val)
            head = head.Next
        }
    
        fmt.Printf("%d\n", head.Val)
    
    }
    

    相关文章

      网友评论

          本文标题:AddTwo Go写法

          本文链接:https://www.haomeiwen.com/subject/rthvmhtx.html