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.