2.add-two-numbers, golang

code:

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
    if nil == l1 {
        return l2
    } else if nil == l2 {
        return l1
    }
    
    temp1, temp2 := l1, l2
    var pRet, pLastNode *ListNode = nil, nil
    var nCarry int = 0
    var nSum int = 0
    var nRemainer int = 0
    
    for nil != temp1 || nil != temp2 {
        if nil == temp1 {
            pRet = l2
            nSum = temp2.Val + nCarry 
            nCarry = nSum / 10
            temp2.Val = nSum % 10
            pLastNode = temp2
            temp2 = temp2.Next
        } else if nil == temp2 {
            pRet = l1
            nSum = temp1.Val + nCarry 
            nCarry = nSum / 10
            temp1.Val = nSum % 10
            pLastNode = temp1
            temp1 = temp1.Next
        } else {
            nSum = temp1.Val + temp2.Val + nCarry 
            nCarry = nSum / 10
            nRemainer = nSum % 10
            temp1.Val, temp2.Val = nRemainer, nRemainer
            pLastNode = temp1
            temp1, temp2 = temp1.Next, temp2.Next
        }
    }//for nil != temp1 || nil != temp2
    
    //fmt.Printf("nCarry:%d, pRet:%v\n", nCarry, pRet)
    if 0 != nCarry {
        pNewLastNode := new(ListNode)
        pNewLastNode.Val, pNewLastNode.Next = nCarry, nil
        pLastNode.Next = pNewLastNode
    }
    
    if nil == pRet {
        pRet = l1
    }
    
    return pRet
}

result:
在这里插入图片描述
personal opinion:
Go language don’t have something like “var1 = var2 = 2” and “pRet == nil ? pL1 : pL2”.It is very inconvenient.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值