美文网首页
add two nums

add two nums

作者: 博林木木 | 来源:发表于2016-12-16 17:11 被阅读0次
    package main
    
    import "fmt"
    
    type ListNode struct {
         Val int
         Next *ListNode
     }
    
    func main() {
        var l1 *ListNode
        var l2 *ListNode
    
    
        l1 = &ListNode{
            Val:5,
            Next:&ListNode{
                Val:8,
                Next:&ListNode{
                    Val:3,
                },
            },
        }
    
        l2 = &ListNode{
            Val:5,
            Next:&ListNode{
                Val:6,
                Next:&ListNode{
                    Val:4,
                },
            },
        }
        res := addTwoNumbers(l1,l2)
        fmt.Println(res)
    
    }
    /**
     * Definition for singly-linked list.
     * type ListNode struct {
     *     Val int
     *     Next *ListNode
     * }
     */
    func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode{
    
        var l1List []int
        var l2List []int
        for tmp1 := l1;tmp1 != nil ;tmp1 = tmp1.Next {
            l1List = append(l1List,tmp1.Val)
        }
        for tmp2 := l2;tmp2 != nil ;tmp2 = tmp2.Next {
            l2List = append(l2List,tmp2.Val)
        }
        rem := 0
        var res *ListNode
        var resTmp *ListNode
    
        maxLen := 0
        if len(l1List) > len(l2List){
            maxLen = len(l1List)+1
        }else {
            maxLen = len(l2List)+1
        }
    
        for i := 0;i<maxLen;i++{
    
            l1Value := 0
            if i>=len(l1List){
                l1Value = 0
            }else{
                l1Value = l1List[i]
            }
    
            l2Value := 0
            if i>=len(l2List){
                l2Value = 0
            }else{
                l2Value = l2List[i]
            }
            count := l1Value + l2Value + rem
    
            sum := 0
            if count>=10{
                rem = 1
                sum = count-10
            }else{
                rem = 0
                sum = count
            }
    
            if sum !=0 || i != maxLen-1{
    
    
                if res == nil{
                    res = &ListNode{
                        Val:sum,
                    }
                    resTmp = res
                }else{
                    resTmp.Next = &ListNode{
                        Val:sum,
                    }
                    resTmp = resTmp.Next
                }
    
            }
    
        }
    
        return res
    
    }
    

    相关文章

      网友评论

          本文标题:add two nums

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