AddTwo Go写法
2020-04-12 本文已影响0人
FredricZhu
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)
}