package main import ( "fmt" ) func main() { //var l1 = &ListNode{ // 2, &ListNode{4, &ListNode{3, nil}}, //} //var l2 = &ListNode{ // 5, &ListNode{6, &ListNode{4, nil}}, //} var l1 = &ListNode{ 9, nil, } var l2 *ListNode var l2Cuosor *ListNode for i := 0; i < 10; i++ { if i == 0 { l2 = &ListNode{1, nil} l2Cuosor = l2 continue } var temp = &ListNode{9, nil} l2Cuosor.Next = temp l2Cuosor = l2Cuosor.Next } // [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1] //[5,6,4] var result = addTwoNumbers(l1, l2) listPrint(result) } /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ type ListNode struct { Val int Next *ListNode } func listPrint(list *ListNode) { for list != nil { fmt.Printf("%v", list.Val) if list.Next == nil { break } fmt.Printf(" -> ") list = list.Next } } func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode { var l1Tmp, l2Tmp = l1, l2 var result, resultTemp, lastNode *ListNode var carry int = 0 for l1Tmp != nil && l2Tmp != nil { var value = l1Tmp.Val + l2Tmp.Val + carry tmp := &ListNode{ Val: value % 10, Next: nil, } carry = value / 10 if resultTemp == nil { resultTemp = tmp result = resultTemp } else { resultTemp.Next = tmp resultTemp = resultTemp.Next } lastNode = l1Tmp.Next if l1Tmp.Next == nil { lastNode = l2Tmp.Next } l1Tmp = l1Tmp.Next l2Tmp = l2Tmp.Next } for lastNode != nil { var value = lastNode.Val + carry var tmp = &ListNode{ Val: value % 10, Next: nil, } carry = value / 10 if resultTemp == nil { resultTemp = tmp result = resultTemp } else { resultTemp.Next = tmp resultTemp = resultTemp.Next } lastNode = lastNode.Next } if carry != 0 { tmp := &ListNode{Val: carry, Next: nil} resultTemp.Next = tmp resultTemp = resultTemp.Next } return result }