-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
92 lines (85 loc) · 1.19 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package main
import (
"fmt"
)
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
type ListNode struct {
Val int
Next *ListNode
}
func (l *ListNode) String() string {
return fmt.Sprintf("%d, %v", l.Val, l.Next)
}
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
var (
ten int
num int
head *ListNode
list *ListNode
next *ListNode
)
for l1 != nil || l2 != nil {
num = 0
if l1 != nil {
num += l1.Val
l1 = l1.Next
}
if l2 != nil {
num += l2.Val
l2 = l2.Next
}
num += ten
next = &ListNode{
Val: num % 10,
Next: nil,
}
if head == nil {
head = next
list = head
} else {
list.Next = next
list = list.Next
}
ten = num / 10
}
if ten != 0 {
list.Next = &ListNode{
Val: ten,
Next: nil,
}
}
return head
}
func main() {
list1 := &ListNode{
Val: 2,
Next: &ListNode{
Val: 4,
Next: &ListNode{
Val: 9,
Next: nil,
},
},
}
list2 := &ListNode{
Val: 5,
Next: &ListNode{
Val: 6,
Next: &ListNode{
Val: 4,
Next: &ListNode{
Val: 9,
Next: nil,
},
},
},
}
v := addTwoNumbers(list1, list2)
fmt.Println(v)
}